Javascript area "this" giving different results depending on what it's called

Everything,

This is the code:

var Person = function (name) { this.name = name; this.printName = function(){ console.log("My name is " + this.name); } }; var p = new Person("Steve"); var funcRef = p["printName"]; p.printName();//Works p["printName"]();//Works funcRef();//returns incorrect value 

Find a working example here: http://plnkr.co/edit/57LS6oXPfqccAWf6uqQV?p=preview

My question is what is the difference between the last two? I access the method of the object in the same way, the only difference is what it is called.

Why does it return the difference result?

The first time I came across this in javascript. I understand this in different areas, but I do not know how it separated from the object, which I would like to understand.

thanks

Steve

+6
source share
4 answers

javascript associates the this when directly calling a function on an object.

With test.fn() , this will be test inside fn . Same thing with test['fn']() . But if you do var fn = test.fn; fn() var fn = test.fn; fn() , this will be the global root ( window in the browser) inside fn .

You can force this inside such a function: var fn = test.fn.bind(test);

More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

+5
source

Case1: 'this' always takes the context of the object in relation to which it is called.

In p.printName (), the context is p, so 'this' refers to the Person object to which "p" refers.

Option 2: But, when you direct the funcRef method to p, it loses this context, and 'this' refers to the global object.

The global object may be different depending on the js environment (e.g. browser context or node, etc.).

That is why you see different results.

+2
source

As another answer says, this bound when calling a function. The usual way to save an object reference is to use something like this:

 var Person = function (name) { var self = this; // Keep a reference to this object for later use self.name = name; self.printName = function(){ console.log("My name is " + self.name); } }; 
+2
source

How this scope works is already explained by the answers above, here is the best practice for using 'this', use 'this' as a new variable called "self", see the code below, so you have better control and fewer errors from due to misuse of this area.

 var Person = function (name) { var self=this; self.name = name; self.printName = function(){ console.log("My name is " + self.name); } }; 
+2
source

All Articles