![](/img/trans.png)
[英]Object.getPrototypeOf fail to __proto__ fail to object.constructor.prototype shims
[英]is Object.getPrototypeOf() same as Object.constructor.prototype in Javascript?
Object.getPrototypeOf(obj)
和obj.constructor.prototype
之間有區別嗎? 或者這兩個引用相同的東西?
沒有
它返回內部[[Prototype]]
值。
例如:
var o = Object.create(null);
Object.getPrototypeOf(o); // null
o.constructor.prototype; // error
var p = {};
var o = Object.create(p);
Object.getPrototypeOf(o); // p
o.constructor.prototype; // Object.prototype
o.constructor.prototype
只適用於通過new ConstructorFunction
創建的對象,或者您手動設置Prototype.prototype.constructor === Prototype
關系的對象。
不 。 特別是,對象的constructor
屬性並不總是設置為您認為“正確”的屬性。
getPrototypeOf
工作的示例,但.constructor.prototype
不:
function F() { }
F.prototype = {
foo: "bar"
};
var obj = new F();
assert.equal(obj.constructor.prototype, Object.prototype);
assert.equal(Object.getPrototypeOf(obj), F.prototype);
對於典型的原型繼承方案,它也失敗了:
// G prototypally inherits from F
function G() { }
G.prototype = Object.create(F.prototype);
// or: G.prototype = new F();
var obj2 = new G();
assert.equal(obj2.constructor.prototype, Object.prototype);
assert.equal(Object.getPrototypeOf(obj2), G.prototype);
assert.equal(Object.getPrototypeOf(Object.getPrototypeOf(obj2)), F.prototype);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.