简体   繁体   中英

Why this javascript code not working?

This code work :

    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 

But why this not working :

     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"

You can't set the prototype inside of the function like that. When invoking a function with the new operator, then a new object is created, and this gets set to that object. Objects don't have a publicly accessible prototype property that you can set. Their prototype property is actually __proto__ , which is not accessible (although some browsers do let you get at it).

In your second example, you're just setting a plain ol' vanilla property named "prototype" with a value.

the prototype property on a function is also not the prototype! Confusing, eh? What it really is is something of a "prototype template". It basically means "when you create an object using this function as the constructor, set their prototype to whatever I have set in the prototype property." This can be very confusing until you grok it.

Also Note

Your first example doesn't work either ( try it here ), you are setting the prototype property of the function after the instance was already created. So that instance was already given a different prototype object. If you created a second instance of class2 , it would alert the property correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM