基本上,this指的是当前正在执行或调用该函数的对象的值。this值的变化取决于我们使用 它的上下文和我们在哪里使用它。
const carDetails = {
name: "Ford Mustang",
yearBought: 2005,
getName () {
return this. name;
},
isRegistered: true
};
console. log(carDetails. getName()); // Ford Mustang
这通常是我们期望结果的,因为在getName方法中我们返回this. name,在此上下文中,this 指向的是carDetails对象,该对象当前是执行函数的“所有者”对象。
接下我们做些奇怪的事情:
var name = "Ford Ranger";
var getCarName = carDetails. getName;
console. log(getCarName()); // Ford Ranger
上面打印Ford Ranger,这很奇怪,因为在第一个console, log语句中打印的是Ford Mustango 这样做的原因是getCarName方法有一个不同的“所有者”对象,即window对象。在全局作用 域中使用var关键字声明变量会在window对象中附加与变量名称相同的属性。请记住,当没 有使用"use strict"时,在全局作用域中this指的是window对象。
console. log(getCarName === window. getCarName) ; // true console, log (getCarName ===
this. getCarName); // true
本例中的this和window引用同一个对象。
解决这个问题的一种方法是在函数中使用apply和call方法。
console. log(getCarName. apply(carDetails)) ; // Ford Mustang console. log(getCarName. call (carDetails)) ; // Ford Mustang apply和call方法期望第一个参数是一个对象,该对象是函数内部this的值。
IIFE或立即执行的函数表达式,在全局作用域内声明的函数,对象内部方法中的匿名函数和 内部函数的this具有默认值,该值指向window对象。
(function () {
console. log(this);
}) 0; // 打印"window"对象
function iHateThis(){
console. log(this);
}
iHateThis();//打印“window”对象
const myFavoriteObj = {
guessThis() {
function getName(){
console. log (this, name);
}
getName ();
},
name: ‘Marko Polo’,
thisIsAnnoying(callback){
callback ();
}
};
myFavoriteObj. guessThisO; // 打印"window"对象
myFavoriteObj. thisIsAnnoying(function () {
console. log (this) ; // 打印"window"对象
});
如果我们要获取myFavoriteObj对象中的name属性(即Marko Polo)的值,则有两种方法可 以解决此问题。
一种是将this值保存在变量中。
const myFavoriteObj = {
guessThis() {
const self = this; // 把 this 值保存在 self 变量中
function getName(){
console. log(self. name);
}
getName ();
}, name: ‘ Marko Polo’, thisIsAnnoying(callback) {
callback() ;
}
};
第二种方式是使用箭头函数
const myFavoriteObj = {
guessThis () {
const getName =()=>{
console. log(this. name);
}
getName();
},
name: ‘Marko Polo’,
thisIsAnnoying(callback) {
callback() ;
}
};
箭头函数没有自己的this。它复制了这个封闭的词法作用域中this值,在这个例子中,this 值在getName内部函数之外,也就是myFavoriteObj对象!
Was this helpful?
1 / 0