Nodejs中怎样用 JS 自身实现一遍 new ?
Nodejs中怎样用 JS 自身实现一遍 new ?
比如一个函数, generate()
, 使得下面两个表达式意义相同:
b = new a;
b = generate(a);
12 回复
在JavaScript中,new
操作符用于创建一个用户定义的对象的实例或具有构造函数的内置对象的实例。为了模拟new
操作符的功能,我们可以自己编写一个函数来实现类似的行为。我们可以通过这个函数接受一个构造函数和任意数量的参数,然后返回一个新的对象实例。
示例代码
function generate(constructor, ...args) {
// 检查传入的是否是一个函数
if (typeof constructor !== 'function') {
throw new TypeError('First argument must be a constructor function');
}
// 创建一个新对象,并继承构造函数的原型
const obj = Object.create(constructor.prototype);
// 调用构造函数并传入参数
const result = constructor.apply(obj, args);
// 如果构造函数返回的是一个对象,则直接使用该对象
return (result != null && (typeof result === 'object' || typeof result === 'function'))
? result
: obj;
}
// 示例构造函数
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
// 使用generate函数
const person = generate(Person, 'Alice', 30);
// 测试
person.greet(); // 输出: Hello, my name is Alice and I am 30 years old.
解释
- 检查类型:首先,我们确保传入的第一个参数是一个函数。如果不是,抛出一个类型错误。
- 创建对象:使用
Object.create()
方法创建一个新对象,并将其原型设置为构造函数的原型。这样新对象就可以访问构造函数原型上的属性和方法了。 - 调用构造函数:使用
apply()
方法调用构造函数,并将新创建的对象作为上下文传递给构造函数。同时传递所有额外的参数。 - 返回结果:如果构造函数返回了一个对象(包括null),则返回该对象;否则,返回新创建的对象。
通过这种方式,我们能够模仿new
操作符的行为,创建并初始化新的对象实例。
function generate (fn) {
return new fn;
}
… 这不科学…
这个问题本来就是闲得蛋疼才想出来的
function generate = (ctor, args){
var o = clone(ctor.prototype)
ctor.apply(o, args)
}
clone.toString() == ?
想做什么
想学会折腾原型链
function generate (ctor){ var o = {}; ctor.call(o); ctor.proto = ctor.prototype;
return o; }
generate = (ctor, arg...)->
o = {}
o.__proto__ = ctor.prototype
ctor.apply o, arg
o
class Dog
constructor:(@name)->
eat:->
console.log "#{@name} is eatting"
generate(Dog, "dogg").eat()
要实现 generate()
函数,使得 b = new a()
和 b = generate(a)
的效果相同,我们需要模仿 JavaScript 中 new
操作符的工作原理。new
操作符主要有以下几个步骤:
- 创建一个新的空对象。
- 将这个新对象的原型设置为构造函数的
prototype
属性。 - 将构造函数的作用域赋给新对象(即
this
指向新对象)。 - 执行构造函数中的代码(为新对象添加属性)。
- 如果构造函数返回了一个对象,则返回该对象;否则返回新对象。
我们可以将这些步骤封装到一个 generate
函数中,以便实现相同的效果。以下是实现代码:
function generate(constructorFn, ...args) {
// 1. 创建一个新的空对象
const obj = {};
// 2. 将这个新对象的原型设置为构造函数的 prototype 属性
if (constructorFn.prototype) {
Object.setPrototypeOf(obj, constructorFn.prototype);
}
// 3. 将构造函数的作用域赋给新对象(即 this 指向新对象)
const result = constructorFn.apply(obj, args);
// 4. 如果构造函数返回了一个对象,则返回该对象;否则返回新对象
return result instanceof Object ? result : obj;
}
使用示例:
function Person(name) {
this.name = name;
}
const personInstance = generate(Person, 'John Doe');
console.log(personInstance instanceof Person); // true
console.log(personInstance.name); // John Doe
在这个例子中,我们创建了一个 Person
构造函数,并使用 generate
函数来实例化它。generate
函数的输出与 new
操作符的效果相同。