Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prototype based variable scope, `new` operator in JavaScript

Tags:

javascript

oop

I would like to know, is the scope of variables in when creating object with use of new operator in JavaScript?

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

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

case 1 : I understood this

// assign again prototype a property as 2 
A.prototype.a = 2 ;// prototype property

var obj = new A();

console.log( obj instanceof A );
console.log( obj.a == 1 ); 

case 2 : Changed A constructor into B reference

A.prototype.constructor =  B;
A.prototype.a = 2 ;// prototype property


var obj = new A();
console.log( obj instanceof B ); // false, as I 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 , as I expected
console.log( obj.a == 1 ); // still 1 why ?

I have done some research, but could not find correct explanation for this .

like image 892
rab Avatar asked Sep 23 '26 20:09

rab


1 Answers

Prototype assigns/binds to the object before the objects initialization code is run

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

Inside the functions initialization code, before the prototype for A.a was assigned the first console.log was undefined. After prototype A.a was assigned the first consol.log correctly display it as (2) then this.a was assigned as 1 and the second console.log correctly displayed it as (1)

like image 90
Louis Ricci Avatar answered Sep 26 '26 10:09

Louis Ricci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!