为什么我不能从 A 访问“x”属性?
A = {}; B = {y: 'y'}; C = {x: 'x'}; A.prototype = B; B.prototype = C; A.x
最佳答案
prototype
属性不反射(reflect)对象的原型(prototype)(尽管这可能会令人困惑)。事实上,在创建对象后,没有标准的、直接的方法来设置对象的原型(prototype)(而且直到最近才有检索对象原型(prototype)的标准方法)。在您引用的代码中,您所做的只是在对象上创建一个名为 prototype
的普通属性;它也可能被称为 foo
。 :-)
在 JavaScript 中有一个特殊的 prototype
属性,但它在 functions 上:它是将被分配为原型(prototype)的对象由该函数创建的对象,如果您将它与 new
关键字一起使用(例如,作为 构造函数)。事实上,直到最近,将原型(prototype)分配给对象的唯一方法是通过构造函数:
function makeA() {
}
makeA.prototype.x = "foo";
A = new makeA();
alert(A.x); // alerts "foo"
...这仍然是唯一得到广泛支持的方法。
随着新的 ECMAScript 5th edition specification 的出现,情况略有变化。 , 但您仍然只能在创建对象时设置对象的原型(prototype),而不是事后。新东西所做的是使直接执行它成为可能,而不是通过构造函数来执行它。这是第 15.2.3.5 节中的新 Object.create
功能,但尚未得到广泛支持。 (第 5 版还有其他几个漂亮的功能,包括通过 Object.getPrototypeOf
get 对象原型(prototype)的能力;但在事实上。)
有些实现(如 Firefox 的 SpiderMonkey 引擎)提供了一个非标准属性,__proto__
,但它没有得到广泛支持,也没有包含在最新规范中.
使用新的 Object.create
,你可以像这样做你想做的事:
var C = {x: 'x'};
var B = Object.create(C);
B.y = 'y';
var A = Object.create(B);
alert(A.x); // alerts "x"
...但是由于 Object.create
太新了,您会发现在大多数实现中,您需要创建它,因为它不存在。如果我们忽略它的第二个参数(只能部分模拟),这就很容易了:
if (!Object.create) {
// An *incomplete* emulation of Object.create, doesn't support the optional
// second parameter defined by the spec.
Object.create = function(proto) {
var obj;
// There's no point in calling this with a null or otherwise "falsy"
// prototype, but let's handle it if you do
if (!proto) {
return {}; // Just a generic object
}
// Define a constructor object that uses
// the prototype
function ctor() {
}
ctor.prototype = proto;
// Create and return the object
return new ctor();
};
}
关于javascript - JavaScript 中原型(prototype)链的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4064716/