Javascript this 关键字 详解(2)
var x = 100;
var obj = {
x: 10,
output: function() {
return this.x;
}
};
//Outputs: 10
console.log(obj.output());
var obj2 = {
x: 40,
output: obj.output
}
//Outputs: 40
console.log(obj.output.call(obj2));
//Outputs: 10
console.log(obj2.output.apply(obj));
五、callback函数內的this指向调用该callback的函数的this所指向的对象
//<input type="text" value="3" id="txt_username">
$("#username").on("click", function() {
console.log(this.value);
});
六、Function.prototype.bind中的this
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
实例一:
function person() {
return this.name;
}
//Function.prototype.bind
var per = person.bind({
name: "zuojj"
});
console.log(per);
var obj = {
name: "Ben",
person: person,
per: per
};
//Outputs: Ben, zuojj
console.log(obj.person(), obj.per());
实例二:
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
//Outputs: 81
console.log(module.getX());
var getX = module.getX;
//Outputs: 9, because in this case, "this" refers to the global object
console.log(getX);
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
//Outputs: 81
console.log(boundGetX());