All,
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's the difference between the last two? I'm accessing the object method in the same way, the only difference is the way it's being called.
Why does it return a difference result?
First time I have come across this in javascript. I understand it's in a difference scope but i don't know how it got decoupled from the object which is what I'd like to understand.
Thanks
Steve
JavaScript has two scopes: global and local. Local scope has two variations: the old function scope, and the new block scope introduced with ES6. It's worth noting that function scope is actually a special type of a block scope.
JavaScript has 3 types of scope: Block scope. Function scope. Global scope.
'Polluting' the global scope means that you define too many variables that are globally accessible. From a programming perspective, you make it difficult to debug and maintain code when you use global variables.
The lexical scope allows a function scope to access statically the variables from the outer scopes. Finally, a closure is a function that captures variables from its lexical scope. In simple words, the closure remembers the variables from the place where it is defined, no matter where it is executed.
javascript bind the this
keyword when you call the function on the object directly.
With test.fn()
, this
will be test
inside fn
. Same with test['fn']()
. But if you do var fn = test.fn; fn()
, this
will be the global root (window
in a browser) inside fn
.
You can force the this
inside a function like this : var fn = test.fn.bind(test);
More informations here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Case1 : 'this' always takes the context of the object with respect to which its called.
In p.printName() the context is p therefore 'this' references the Person object that 'p' refers to.
Case2: But, when you direct 'funcRef' to p's method it loses this context and 'this' references the global object.
The global object can be different depending on your js environment (like the browser context or node and so on).
That is why you see different results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With