Why this behaviour?__proto__ vs prototype?

前端 未结 3 881
南旧
南旧 2021-01-15 10:28
    function Obj1(name){
        this.__proto__={
            Name:name,
            getName:function(){
                alert(this.Name); 
            }


        }         


        
3条回答
  •  时光说笑
    2021-01-15 10:37

    __proto__ (which is not standard (but might be soon))) sets an object's prototype.

    .prototype sets the prototype of objects created by invoking the function it was set on as a constructor using new

    Also worth mentioning is Object.create

    Here are examples:

    Pseudo-classical with .prototype:

    function Car(){
       this.x = 15;
    }
    Car.prototype.y = 10;
    
    var g = new Car();
    g.y; // this is 10;
    

    Using __proto__ (don't use this!):

    var g = {x:15};
    g.__proto__ = {y:10};
    g.y; // this is 10;
    

    This way is correct, and does not use constructors with new:

    var g = Object.create({y:10}); //creates x with prototype {y:10}
    g.x = 15;
    g.y; // this is 10
    

    Here is an interesting tutorial on MDN covering these.

提交回复
热议问题