var f = function () {
return this;
};
console.log(f.apply(location.hash)); // Sets a custom this value for the function.
Example #2 – apply example
var getName = function () {
return this.name.first + ' ' + this.name.last;
}
var lars = {
name: {
first: 'Lars',
last: 'Doe'
}
};
console.log(getName.apply(lars));
Example #3 – apply example
var getName = function (lastFirst, includeAge) {
var result = '';
if (lastFirst) {
result = this.name.last + ', ' + this.name.first;
}
else {
result = this.name.first + ' ' + this.name.last;
}
if (includeAge) {
result += ' (' + this.age + ')';
}
return result;
}
var lars = {
name: {
first: 'Lars',
last: 'Doe'
},
age: 20
};
console.log(getName.apply(lars)); // Lars Doe
console.log(getName.apply(lars, [true])); // Doe, Lars
console.log(getName.apply(lars, [false, true])); // Lars Doe (20)