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

Tus*_*rao 0 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 
Run Code Online (Sandbox Code Playgroud)

但为什么这不起作用:

     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"
Run Code Online (Sandbox Code Playgroud)

Mat*_*eer 5

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

在您的第二个示例中,您只需使用值设置名为"prototype"的普通ol'vanilla属性.

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

另请注意

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