this is determined by the calling context, the way in which function is called.
Calling standalone functions directly
When a function is executed as a simple object function directly, this refers to the global object.function foo() {
console.log('Hello World!');
console.log(this);
}
foo();
Calling functions as property of an object reference
Here we have created an object obj, and there is a property on it which is a function. The function is being called as a property on the object. Here this refers to the object obj itself.var obj = {};
obj.foo = function() {
console.log('Hello World!');
console.log(this);
}
obj.foo();
Calling standalone functions using 'new' keyword
When a function is called using the new keyword, this always refer to the newly created object, an empty object.function foo() {
console.log('Hello World!');
console.log(this);
}
new foo();
0 comments:
Post a Comment