Javascript: Self and This
Asked Answered
I

2

7

Can anyone explain why do I get different values of self 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've been using self on project and it's my first time to have this issue.

Indelicacy answered 25/2, 2013 at 9:27 Comment(4)
self and this are no longer referring to the same object. The following link may be helpful : #962533Jurisconsult
ô the joy of javascript call context !Verbal
In func, it seems like self points to the Parent, but this points to the Child.Beaded
Thanks for the answers. This is why I like javascript, very different. Now I need to be more careful on nested callbacks.Indelicacy
F
9

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

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

So when you call func on an instance of Child, this refers to that instance. That's why this.a gives you the correct value inside func.

Fabyola answered 25/2, 2013 at 9:34 Comment(0)
L
1

Within func, this refers to an instance of Child.

Child.prototype.__proto__ = new Parent;

The prototype of Child is set to an instance of Parent. So when ch.func() is invoked, func() is on the prototype chain of Child, but is invoked in the context of ch which is an instance of Child

self is still referring to the instance of Parent which does not have an attribute a

To further illustrate:

var p = new Parent();

// this.a is undefined because this is an instance of Parent
p.func(); // undefined undefined
Limulus answered 25/2, 2013 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.