3

我正在尝试制作一些好的代码示例来体验 JavaScript 的“无类”。到目前为止,这是我想出的:

function One() {}
function Two() {}

One.prototype.a = 5;
Two.prototype.b = 4;

var obj = new One();
print("1) ctor =", obj.constructor, "a =", obj.a, " b =", obj.b);
obj.constructor = Two;
print("1) ctor =", obj.constructor, "a =", obj.a, " b =", obj.b);

var objTwo = new obj.constructor();
print("2) ctor =", objTwo.constructor, "a =", objTwo.a, " b =", objTwo.b);

这些是相应的打印:

1) ctor = function One() {
} a = 5  b = undefined
1) ctor = function Two() {
} a = 5  b = undefined
2) ctor = function Two() {
} a = undefined  b = 4

我的问题是为什么原型链在这里不起作用?我使用 JavaScript (spidermonkey) (spidermonkey-1.7) 在 ideone 中运行我的示例。看起来在现实生活中原型是通过其他方式访问的constructor.prototype

PS 进一步的实验表明,分配给obj.constructor添加了新属性,这会影响原始属性。为什么?..

4

3 回答 3

1

是的,有Object.__proto__和直接Object.prototype。如果您打印 One.prototype,您应该会看到所需的结果。如果你这样做console.dir(someInstance);,你会得到直接在下面列出的实例变量someInstance

之后,您可以展开prototype并且您将看到您为该原型定义的方法。(例如One.prototype.doSomething = function(a){});

在此处阅读有关Object.__proto__它的更多信息,并在此处阅读有关Object.prototype(标准)的更多信息。

于 2013-04-08T09:28:46.410 回答
1

Initially, your var obj doesn't have a property named constructor. When you print it, it's resolved via its prototype (One.prototype) -- all prototypes have a constructor. When you assign obj.constructor = Two you create an own property in obj which shadows the prototype property. This new prop means nothing to the engine and doesn't affect inheritance in any way.

In general, "constructor" appears to be a pure informative property and doesn't serve any particular purpose. It's just a backlink from a function's prototype back to the parent function. See Creating functions and Construct for further reference.

于 2013-04-08T10:13:32.357 回答
0

这里的问题是你进入了机械系统,然后开始拉线。书中没有真正发生在这里,因为你通过注入这个指针破坏了自然序列

obj.constructor = Two;

这不是进行继承的正确方法。这是:

function One() {}
function Two() {}

One.prototype.a = 5;
Two.prototype = new One();
Two.prototype.b = 4;

Now any object instantiated with new Two() will show the is-a relationship (inheritance) properly in the constructor. Here is a jsFiddle Demo showing the difference.

于 2013-04-08T09:38:26.697 回答