var name = "This Window";
var obj = {
name: 'This Object',
getFunction: function () {
return function () {
return this.name;
}
}
}
console.log(obj.getFunction()());//This Window
不改变this的情况下,输出结果为 This Window.
一、 通过在父函数设置临时变量 存储父函数中this。让this指向父级函数。
var name = "This Window";
var obj = {
name: 'This Object',
getFunction: function () {
let that = this;
return function () {
return that.name;
}
}
}
console.log(obj.getFunction()());//This Object
二、直接使用箭头函数来改变this指向 ,让this指向父级函数
var name = "This Window";
var obj = {
name: 'This Object',
getFunction: function () {
return () => {
return this.name;
}
}
}
console.log(obj.getFunction()());//This Object
三、call( )函数
var name = "This Window";
var obj = {
name: 'This Object',
getFunction: function () {
return function () {
return this.name;
}
}
}
console.log(obj.getFunction()());//This Window
console.log(obj.getFunction().call(obj));//This Object
四、apply( )函数
var name = "This Window";
var obj = {
name: 'This Object',
getFunction: function () {
return function () {
return this.name;
}
}
}
console.log(obj.getFunction()());//This Window
console.log(obj.getFunction().apply(obj));//This Object
五、bind( )函数(注意需手动调用)
var name = "This Window";
var obj = {
name: 'This Object',
getFunction: function () {
return function () {
return this.name;
}
}
}
console.log(obj.getFunction()());//This Window
console.log(obj.getFunction().bind(obj)());//This Object
var name = "This Window"; var obj = { name: 'This Object', getFunction: function () { return function () { return this.name; } } }console.log(obj.getFunction()()..