此代码有效:
function class1(){
this.x5 = 5;
this.x6 = 6;
this.prototype = 5;
}
function class2(){
this.x3 = 3;
this.x4 = 4;
}
class2.prototype = new class1();
var obj1 = new class2();
alert(obj1.x5 ); // alert me 5
但是为什么这不起作用:
function class1(){
this.x5 = 5;
this.x6 = 6;
this.prototype = 5;
}
function class2(){
this.x3 = 3;
this.x4 = 4;
this.prototype = new class1(); // or class2.prototype = new class1();
}
var obj1 = new class2();
alert(obj1.x5); // alert me "undefinded"
最佳答案
你不能像这样在函数内部设置原型(prototype)。当使用 new 运算符调用函数时,会创建一个新对象,并将 this 设置为该对象。对象没有可以设置的可公开访问的原型(prototype)属性。它们的原型(prototype)属性实际上是 __proto__
,这是不可访问的(尽管有些浏览器确实允许您访问它)。
在第二个示例中,您只需设置一个名为“prototype”的普通属性和一个值。
函数的 prototype
属性也不是原型(prototype)!令人困惑,是吗?它实际上是一个“原型(prototype)模板”。它基本上意味着“当您使用此函数作为构造函数创建对象时,将其原型(prototype)设置为我在 prototype
属性中设置的内容。”在您理解之前,这可能会非常令人困惑。
另请注意
您的第一个示例也不起作用( try it here ),您在创建实例后设置函数的原型(prototype)属性。所以该实例已经被赋予了一个不同的原型(prototype)对象。如果您创建了 class2
的第二个实例,它将正确提醒该属性。
关于javascript - 为什么这段 JavaScript 代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9075505/