The 'this' keyword in JavaScript refers to the owner of the function that is being executed. The value of 'this' is determined by how the function is called. In a global context, 'this' refers to the global object (window). In a constructor function called with 'new', 'this' refers to the newly created object. In event handlers, 'this' refers to the element that received the event. The value of 'this' can be explicitly set by using call, apply, or bind.
3. Definition
this is a special identifier keyword - pointing to
the “owner” of the function being executed.
The value of this is based on the context in
which the function is called at runtime.
11. eval() vs setTimeout()/setInterval()
var obj = {};
obj.testEval = function () {
eval("alert(this)");
};
obj.testSetTimeout = function () {
setTimeout("alert(this)", 100);
};
obj.testEval(); // obj
obj.testSetTimeout(); // window
the setTimeout function
is a method of the
window object.
Any code inside the
anonymous function that
is passed into the
setTimeout call has
window as it’s context
12. Execution
Context
Syntax of function call Value of this
Global n/a global object (e.g. window)
Function Method call:
myObject.foo();
myObject
Function Baseless function call:
foo();
global object (e.g. window)
(undefined in strict mode)
Function Using call:
foo.call(context, myArg);
context
Function Using apply:
foo.apply(context, [myArgs]);
context
Function Constructor with new:
var new Foo = new Foo();
the new instance
(e.g. newFoo)
Evaluation n/a value of this in parent contexteval()
14. Changing ‘this’ context
var obj = {value: 100};
function add(num1, num2){
alert(this.value + num1 + num2);
}
add.call(obj, 200, 300);
add.apply(obj, [200, 300]);
var objAdd= add.bind(obj);
objAdd(200, 300);
15. that = this
var boy = {
name: "Bill",
girlFriends: ["Emma", "Mia", "Ava"],
showGirlFriends: function () {
var that = this;
this.girlFriends.forEach (function (item) {
console.log (that.name + " has a girlfriend called " +
item);
});
}
};
boy.showGirlFriends();