dimanche 1 février 2015

How do you get the "this" of a function?


How do you get the this value of a function from outside the function, without having to call it? For example, the following doesn't work, but illustrates the idea:



// window is this, currently
function foo() {}
console.log(foo.this) // would log the window object.


The MDN documentation for Function.bind() reports that bind() "creates a new function that, when called, has its this keyword set to the provided value". This implies that each function has a "this" associated with it from the ery start.


The question is whether or not that "this" is accessible from outside the function call, because presumably it's "this" reference already exists based on thos MDN docs.


Try this in your console:



var foo = function() {}
var bar = foo.bind(this)
console.log(foo === bar)


The result is false, meaning you now have two functions, not one, and each one has it's own this.


Some have mentioned that the "callsite" determines the this of a function, which doesn't seem to be true. If you run



var obj = {}
function foo() {
console.log(this)
}
function Obj(func) {
console.log(this)
func()
}
new Obj(foo)


Then the callsite for foo is inside a new Obj but it still logs the Window object.


If you run



var obj = {}
function foo() {
console.log(this)
}
foo()
foo.call(obj)
foo.bind(obj)
foo()


Then you'll notice that the this of the original foo function has not changed. Based on this fact, and the MDN docs for bind, call, and apply, we can confidently assume that the this for a Function can never be changed.





Aucun commentaire:

Enregistrer un commentaire