1) The keyword "this" refers to whatever is left of the dot at call-time.
2) If there's nothing to the left of the dot, then "this" is the root scope (e.g. Window).
3) A few functions change the behavior of "this"—bind, call and apply
4) The keyword "new" binds this to the object just created
So if you're using the value of "this" in someFunction...
thing.someFunction(); // this === thing
someFunction(); // this === Window
new someFunction(); // this === the newly created object
It's as simple as that. It's a very useful keyword.Small addendum to your list: "whatever is left of the dot at call-time" is a nice way to explain "base reference" concept, but be wary of non-trivial constructs:
(f = thing.someFunction)(); // this references global object
(function(){return thing.someFunction }())(); // this references global object
eval('thing.someFunction')(); // this references global objectBut it's one of the weirdest thing in javascript, and I'd advise to forgo using 'this' in any situation that doesn't absolutely need it.
I feel it's the same as class systems with inheritance and lots of OO properties implemented. It's not wrong, but it's so much overhead, so easy to shoot one's foot, for so few returns. And there's a class syntax coming to ES6, so I'm clearly in the minority.
For a discussion on the "this" use, there is an interesting talk[0] by D.Crockford on the subject, at about 8 min in (but I'd watch the whole thing). I don't agree with everything he is advising, but I think he has pretty compelling arguments overall.
There's a lot of things in js that are not necessary to write good code, and avoiding them can reduce a lot of the complexity IMO. Some people are OK with complexity and want expressivity, I'd prefer basic and predictable easily behaviours.
[0] https://www.youtube.com/watch?v=PSGEjv3Tqo0&noredirect=1
o={ f: function() setTimeout(1000,console.log(this)) }
o.f()
http://jsfiddle.net/5bh7yot5/But first, let me fix some errors in your code.
You probably meant to write syntactically correct code, so first line changes to following:
o={ f: function() { setTimeout(1000,console.log(this)) } }
Then, you probably meant to call console.log after one second, not running it immediately and passing result to timeout argument, and passing 1000 as a callback argument.So the code changes to:
o={ f: function() { setTimeout(function() { console.log(this); }, 1000); } }
o.f()
Okay. So what happens now is that- You create and object with property 'f'
- You call the function stored within that property
- Within Execution Context of that function call, `this` is going to be equal to our object. Note that we have not yet used `this`.
- We call setTimeout, passing it function as a callback.
- After one second, that function is called, with new Execution Context, not equal to the first one. `this` there is equal to global scope variable.
Basically your code is doing this right now:
o.f = function(){
console.log(this); // logs `o`, returns `undefined`
setTimeout(1000, undefined);
});
If you did this: o.f = function(){
setTimeout(1000, function(){
console.log(this);
});
};
Then it'd be `Window` as in rule #2.I don't actually. (I'm the author) I know that the this key word is executed at run time to figure out what this is. It is true there are simpler ways to explain this and this blog post isn't that. I link to such a post at the bottom of my own. These are just some examples. There's also more to that blog post than what everyone is discussing, like returning from a constructor and global this in node.js and accessing this in eval and more. Anyway, I didn't submit this to HN and hadn't intended to. I also didn't intend to sit here tonight and put on a thick skin to deal with all this criticism for something I wrote months ago.
To me, 'this' is JS is a lot more self explanatory than this is Java. And your article doesn't make that apparent. In JS this is just another object, like any other object. It follows the exact same scoping rules as every other object.
You are mistaken, "this" is not an object nor a variable, it's a keyword and behaves differently than variable scope. Consider closures for example.
Even knowing this rule very well and being totally hard core OCO (Obsessive Compulsive ORDER, not Disorder) about the code, I still make "this" mistake ALL THE TIME, so whenever something weird happens, "this" mistakes are the first thing I look for.
"this" is such a terrible design flaw, it bites me even when I'm expecting it.
It enables some rather elegant patterns, actually.
Please give me one example of using "this" outside of lexical context, that is impossible or tangibly inconvenient to do by some other technique that JavaScript already supports.
At that point you might as well just redesign the language from scratch, which maybe you'd appreciate.
Guess I'm just not feeling the hate on this one.
function foo() {
var bar = function() {
console.log(this);
};
return bar.bind(42);
}
foo().call(1337); // prints 42
...which behaves as expected, so I'm not sure what you're getting at?You have to REMEMBER that you need to explicitly and inconveniently tell the function which "this" to use, by drilling down into Function.prototype.call/apply, even though it LOOKS like it will simply work like any other variable, which it doesn't.
Please consider that programmers are not perfect, and do not have infinite time or unlimited memory or perfectly focused and undistracted attention, and programming languages are user interfaces for imperfect humans, that should minimize the likelihood of errors, not set traps for less experienced programmers to make obvious mistakes, just so that more experienced programmers can gloat over how much smarter they are for having memorized every detail of the language spec. (-; I'm looking at you, automatically inserted semicolon! ;-)
And my point is that I AM an experienced programmer who has memorized every detail of the JavaScript language spec and uses it all the time, yet I STILL make "this" mistakes AGAIN and AGAIN. While on the other hand, I don't think I've ever made a "self" mistake with Python.
obj.method();
is a sugar for obj.method.call(obj);
Similarly, this picture helped me understand `bind`:http://i.stack.imgur.com/StZOr.png
The a-ha moment for JS is when you realize it's a way simpler language than you thought it was.
new method()
is syntactic sugar for something like var _tmp = {};
_tmp.__proto__ = method.prototype;
_tmp.call(method);
You can use this in any function on an object to refer to other properties on that object. This is not the same as an instance created with new. ... Note, there was no use of new , no Object.create and no function called to create obj.
This is exactly the same behavior that you see on an object method reference, and drawing any distinction at all makes understanding the behavior of this harder than it needs to be.
In nearly every case (with the exception of bind, call and apply) the this variable is set at the CALL SITE of the function, NOT THE DEFINITION. Note that in the three other cases, you still aren't setting this at the definition.
The reason you get this behaving as the author describes on objects created with new is only (as the author nearly, but not quite, realizes) because you called the function in the form:
Specifically, it is the object reference that sets the this context within the method call.You can be sure that the object literal case is just the same. You don't need to call new to get an object reference that has a prototype chain: namely, an object literal is instantiated with the prototype Object. You can verify this is true with a simple:
...and so forth.