This
and
Prototype
This attached
At its fundamental, its the calling context.
var foo = {
bar: 123,
bas: function () {
console.log('inside this.bar is:', this.bar);
}
}
console.log('foo.bar is: ', foo.bar); // foo.bar is: 123
foo.bas(); // inside this.bar is: 123
IMHO better than self in python.
This Global
In the absence of a context ... its window
function foo() {
console.log('is this called from global? : ', this === global); // true
}
foo();
(global is the `window` of nodejs)First Class functions
Just attach a function to an object and you get the *right* this.
var foo = {
bar: 123
};
function bas() {
if (this === global)
console.log('called from global');
if (this === foo)
console.log('called from foo');
}
// global context
bas(); // called from global
// from foo
foo.bas = bas;
foo.bas(); // called from foo
Advantage of calling context
- Makes mixins super easy.
- Allows functions to be shared on the prototype chain
Forcing this Inside a function
All JavaScript functions have "call" "apply" and "bind"
Ways of this
- calling context
- mixins
- shared functions on prototype
- call
- call super functions
- apply
- intercept functions
- bind
- pass member functions around
- new
- Prototype Inheritance 101
ThisandPrototypeold
By basarat
ThisandPrototypeold
- 1,342