在 JavaScript 中,据说对象字面量具有原型(prototype)链接,但是 函数对象同时具有原型(prototype)链接和原型(prototype)属性。
那么,基于以上所述,是否可以说继承(使用原型(prototype)属性)仅适用于函数对象(构造函数版本)而不适用于对象字面量?
此外,要补充的是,__proto__
属性在所有浏览器中都无法访问...
最佳答案
精简版:
是的:不能通过分配给对象的 prototype
属性来设置或修改原型(prototype)链。您不能通过使用对象字面量创建对象然后为其提供名为 prototype
的属性来设置继承。此类属性将称为 prototype
,但不会被视为原型(prototype)继承。
更长:
如果您访问未定义
的属性,则会检查该对象的继承链。因此,如果 obj['prop']
是 undefined
,那么 obj.prototype['prop']
将被检查。在许多浏览器中,prototype
属性在内部实现为 __proto__
属性,但这不是重点。相反,要点是如果某些属性是 undefined
,则会检查对象的原型(prototype)以查找该属性。
正如人们在评论中所说,只有通过将该对象分配给函数的 prototype
属性,然后将该函数用作构造函数。
但是,构造函数调用生成的对象的 prototype
属性不是 object.hasOwnProperty('prototype')
。另一方面,如果您将 prototype
属性分配给一个对象,那么该对象将 object.hasOwnProperty('prototype')
,但是 object.prototype
将与原型(prototype)链无关——它只是一个常规属性,并且会碰巧调用 prototype
。
为了证明这一点:
var foo = {};
foo.prototype = {bar: 'hello'};
console.log(foo.bar); // undefined
console.log(foo.prototype); // Object {bar: "hello"}
console.log(foo.hasOwnProperty('prototype')); // true
var Foo = function() {};
Foo.prototype = {bar: 'hello'};
var f = new Foo;
console.log(f.bar); // 'hello';
console.log(f.hasOwnProperty('bar')); // false
console.log(f.prototype); // undefined
console.log(f.hasOwnProperty('prototype')); // false
关于Javascript 继承和对象字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15264873/