javascript - 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() not function 

what difference between two?some prototype used constructor functions in case doesn't work.... instead __proto__ work why?

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

.prototype sets prototype of objects created invoking function set on constructor using new

also worth mentioning object.create

here examples:

pseudo-classical .prototype:

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

using __proto__ (don't use this!):

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

this way correct, , not use constructors new:

var g = object.create({y:10}); //creates x prototype {y:10} g.x = 15; g.y; // 10 

here an interesting tutorial on mdn covering these.


Comments