Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this behaviour?__proto__ vs prototype?

    function Obj1(name){
        this.__proto__={
            Name:name,
            getName:function(){
                alert(this.Name); 
            }


        };

    }

    function Obj2(name){
       this.prototype={
           Name:name,
           getName:function(){
           alert(this.Name); 
           };


       };

    }
    x=new Obj1("blue shark");
    z=new Obj2("red shark");
    x.getName();
    z.getName();// error:z.getName() is not a function

What is the difference between the two?Some say prototype is used for constructor functions only but in this case it doesn't work.... instead the __proto__ work why?

like image 774
Romantic Electron Avatar asked Feb 09 '26 20:02

Romantic Electron


1 Answers

__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.

like image 110
Benjamin Gruenbaum Avatar answered Feb 15 '26 14:02

Benjamin Gruenbaum