簡體   English   中英

Object.getPrototypeOf()與Javascript中的Object.constructor.prototype相同嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM