oop - prototype based variable scope, `new` operator in JavaScript -


i know, scope of variables in when creating object use of new operator in javascript?

function a(){    this.a = 1; // instance property }  function b(){     this.a = 3; // instance property } 

case 1 : understood this

// assign again prototype property 2  a.prototype.a = 2 ;// prototype property  var obj = new a();  console.log( obj instanceof ); console.log( obj.a == 1 );  

case 2 : changed constructor b reference

a.prototype.constructor =  b; a.prototype.a = 2 ;// prototype property   var obj = new a(); console.log( obj instanceof b ); // false, expected console.log( obj.a == 1 ); // still 1 why ? 

case 3 : inhertiance scope

a.prototype = new b(); a.prototype.a = 4 ;// prototype property   var obj = new a(); console.log( obj instanceof b ); // true , expected console.log( obj.a == 1 ); // still 1 why ? 

i have done research, not find correct explanation .

prototype assigns/binds object before objects initialization code run

> function a() { console.log(this.a); this.a = 1; console.log(this.a); }; undefined > new a(); undefined 1 {a: 1} > a.prototype.a = 2; 2 > new a(); 2 1 {a: 1, a: 2} 

inside functions initialization code, before prototype a.a assigned first console.log undefined. after prototype a.a assigned first consol.log correctly display (2) this.a assigned 1 , second console.log correctly displayed (1)


Comments