Object.Create() 在幕后做什么?
What is Object.Create() doing under the hood?
我正在使用 JavaScript 深入研究原型继承。当 Object.Create() 用于创建对象时,有人可以展示幕后发生的事情吗? Object.Create() 是否依赖于幕后的 new 和构造函数?
Object.create 不调用 "new" 或构造函数。它只是将新对象的原型设置为作为参数传递的对象的原型。
所以
AnotherObject.prototype = Object.create ( Base.prototype )
creates the new object and set AnotherObject.__proto__ to Base.prototype
当您调用 "new" 时,除了调用 "create"(上面)之外,它还会调用 Base class 的构造函数。
要扩展,您可以将新对象的原型扩展为
AnotherObject.prototype.anotherMethod = function() {
// code for another method
};
如果您需要新对象的新构造函数,您可以像这样创建它:
function AnotherObject() {
Base.call(this);
}
AnotherObject.prototype.constructor = AnotherObject;
When Object.create()
is in use to create objects, can someone show what is going on under the hood?
底层细节。 Object.create
几乎是一个原始操作 - 类似于评估 {}
对象文字时发生的情况。试着理解 what it is doing.
也就是说,通过新的 ES6 操作,它可以根据
来实现
function create(proto, descriptors) {
return Object.defineProperties(Object.setPrototypeOf({}, proto), descriptors);
}
Does Object.create()
depend on new
and constructor functions behind the scenes?
不,一点也不。恰恰相反。 new
运算符可以实现为
function new(constructor, arguments) {
var instance = Object.create(constructor.prototype);
constructor.apply(instance, arguments);
return instance;
}
我正在使用 JavaScript 深入研究原型继承。当 Object.Create() 用于创建对象时,有人可以展示幕后发生的事情吗? Object.Create() 是否依赖于幕后的 new 和构造函数?
Object.create 不调用 "new" 或构造函数。它只是将新对象的原型设置为作为参数传递的对象的原型。
所以
AnotherObject.prototype = Object.create ( Base.prototype )
creates the new object and set AnotherObject.__proto__ to Base.prototype
当您调用 "new" 时,除了调用 "create"(上面)之外,它还会调用 Base class 的构造函数。
要扩展,您可以将新对象的原型扩展为
AnotherObject.prototype.anotherMethod = function() {
// code for another method
};
如果您需要新对象的新构造函数,您可以像这样创建它:
function AnotherObject() {
Base.call(this);
}
AnotherObject.prototype.constructor = AnotherObject;
When
Object.create()
is in use to create objects, can someone show what is going on under the hood?
底层细节。 Object.create
几乎是一个原始操作 - 类似于评估 {}
对象文字时发生的情况。试着理解 what it is doing.
也就是说,通过新的 ES6 操作,它可以根据
来实现function create(proto, descriptors) {
return Object.defineProperties(Object.setPrototypeOf({}, proto), descriptors);
}
Does
Object.create()
depend onnew
and constructor functions behind the scenes?
不,一点也不。恰恰相反。 new
运算符可以实现为
function new(constructor, arguments) {
var instance = Object.create(constructor.prototype);
constructor.apply(instance, arguments);
return instance;
}