Javascript: me and this

Can someone explain why I get different meanings of myself and this? Where self is a reference to this.

function Parent(){ var self = this; this.func = function(){ // self.a is undefined // this.a is 'Test' console.log(self.a, this.a); } } function Child(x){ this.a = x; } Child.prototype.__proto__ = new Parent; var ch = new Child('Test'); ch.func(); 

I am using self on project, and this is my first time to have this problem.

+7
source share
2 answers

This is because self refers to the Parent instance, but only Child instances have property a .

 function Parent(){ var self = this; // this is an instance of Parent this.func = function(){ console.log(self.a, this.a); } } function Child(x){ this.a = x; // Instances of Child have an `a` property } Child.prototype.__proto__ = new Parent; var ch = new Child('Test'); ch.func(); // Method called in context of instance of Child 

Therefore, when you call func on an instance of Child , this refers to this instance. Therefore this.a gives the correct value inside func .

+9
source

Inside func , this refers to an instance of Child .

 Child.prototype.__proto__ = new Parent; 

The Child prototype is assigned an instance of Parent . Therefore, when ch.func() is called, func() is in the Child prototype chain, but is called in the context of ch , which is an instance of Child

self still refers to an instance of Parent that does not have an attribute a

For additional illustration:

 var p = new Parent(); // this.a is undefined because this is an instance of Parent p.func(); // undefined undefined 
+1
source

All Articles