为什么这个javascript代码不起作用?

时间:2012-01-31 06:45:06

标签: javascript prototype javascript-objects

此代码工作:

    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"

1 个答案:

答案 0 :(得分:5)

你不能像这样在函数内部设置原型。使用new运算符调用函数时,将创建一个新对象,并将this设置为该对象。对象没有可以设置的可公开访问的原型属性。他们的原型属性实际上是__proto__,这是不可访问的(虽然有些浏览器可以让你得到它)。

在你的第二个例子中,你只是设置一个名为“prototype”的普通ol'vanilla属性,带有一个值。

函数上的prototype属性也不是原型!令人困惑,是吗?它的真正含义是“原型模板”。它基本上意味着“当您使用此函数创建对象作为构造函数时,将其原型设置为我在prototype属性中设置的任何内容。”在你理解之前,这可能会非常令人困惑。

另请注意

您的第一个示例也不起作用(try it here),您在创建实例后设置了该函数的prototype属性。因此该实例已经被赋予了不同的原型对象。如果您创建了class2的第二个实例,它会正确地警告该属性。

相关问题