JavaScript中 this值是什么?
基本上,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 Mustang
。这样做的原因是getCarName
方法有一个不同的“所有者”对象,即window
对象。在全局作用域中使用var
关键字声明变量会在window
对象中附加与变量名称相同的属性。请记住,当没有使用“use strict”
时,在全局作用域中this
指的是window
对象。
console.log(getCarName === window.getCarName); // true console.log(getCarName === this.getCarName); // true
本例中的this
和window
引用同一个对象。
解决这个问题的一种方法是在函数中使用apply
和call
方法。
关于 apply 和 call 方法,推荐阅读之前文章《实例讲解 js 中的 call() apply() bind()的用法和区别》、《深入理解 JavaScript 的 Apply、Call 和 Bind 方法》
console.log(getCarName.apply(carDetails)); // Ford Mustang console.log(getCarName.call(carDetails)); // Ford Mustang
apply
和call
方法期望第一个参数是一个对象,该对象是函数内部this
的值。
IIFE
或立即执行的函数表达式,在全局作用域内声明的函数,对象内部方法中的匿名函数和内部函数的this
具有默认值,该值指向window
对象。
(function() { console.log(this); })(); // 打印 "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.guessThis(); // 打印 "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
对象。
码云笔记 » JavaScript中 this值是什么?