In global scope, this refer to window object but in strict mode, use "this" in global will return "undefined".
var person = {
firstName :"Jack",
lastName :"Diff",
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}
}
person.showFullName (); // Jack Diff
For example:
$ ("#button1").click (function (event) {
console.log ($ (this).prop ("name"));
});
It will return button name of button with selector id : button1
Example:
var person = {
name: 'truong',
getName : function(callback) {
console.log(this); // "this" refers to person object
console.log(this.name);
callback();
}
};
person.getName(function() {
console.log('closure', this); // "this" refers to window object
})
Basically we can change object that "this" refers to by using some special methods: CALL, APPLY, BIND
// BIND
var person = {
name: 'truong',
getName : function(callback) {
console.log(this); // refer to person object
console.log(this.name);
callback();
}
};
var testClosure = function() {
console.log('closure', this); // will refer to person object
}
person.getName(testClosure.bind(person));
"The Apply and Call methods are two of the most often used Function methods in JavaScript, and for good reason: they allow us to borrow functions and set the this value in function invocation. In addition, the apply function in particular allows us to execute a function with an array of parameters, such that each parameter is passed to the function individually when the function executes—great for variadic functions; a variadic function takes varying number of arguments, not a set number of arguments as most functions do." --Javascript.isSexy--
// CALL
var person = {
name: 'truong',
getName : function(nickname) {
console.log(this); // window object
console.log(this.name, nickname); // Global Name my Jack
}
};
var name = "Global Name";
person.getName.call(window, 'my Jack');
// APPLY
var person = {
name: 'truong',
getName : function(callback) {
console.log(this); // person object
console.log(this.name); // truong
callback.apply(window, ['Jack Diff']);
callback.apply(this, ['Jack Diff']);
}
};
var nameCallback = function(nickname) {
console.log(this);
console.log(nickname);
}
person.getName(nameCallback);