全局环境中this
.node中this相当于全局对象 global。
.在JavaScript文件中, this等同于 module.exports而不是 global。
函数中的this
函数中的 this值通常是由函数的调用方来定义。
function rajat() {
//this === window
}
方法中的“this”
当函数作为对象的方法被调用时, this指向的是该对象,也称为函数调用的接收器(receiver)。
const hero = {
heroName: "Batman",
dialogue() {
console.log(`I am ${this.heroName}!`);
}
};
hero.dialogue();
构造函数中的“this”
构造函数被调用时,会创建一个新对象并将其设置为函数的 this参数。构造函数会隐式的返回这个对象,除非我们明确的返回了另外一个对象。
在 hero函数内部添加下面的 return语句:
function Hero(heroName, realName) {
return {
heroName: "Batman",
realName: "Bruce Wayne",
};
}
new Hero();//{heroName: "Batman", realName: "Bruce Wayne"}
function Hero(heroName, realName) {
heroName: "Batman";
realName: "Bruce Wayne";
}
new Hero();//Hero {}
call() 和 apply()
在调用函数时也可以使用 call()和 apply()明确设置 this参数。
function dialogue () {
console.log (`I am ${this.heroName}`);
}
const hero = {
heroName: 'Batman',
};
如果要将 hero对象作为 dialogue函数的接收器,我们可以这样使用 call()或 apply() :
dialogue.call(hero)
// or
dialogue.apply(hero)
bind()
当我们将一个方法作为回调函数传递给另一个函数时,总是存在丢失方法的原有接收器的风险,使得 this参数指向全局对象。
bind()方法可以将 this参数固定的绑定到一个值上。
下面的代码片段, bind会创建一个新的 dialogue函数,并将 this值设置为 hero 。
(译者注:bind()方法会创建一个新函数,称为绑定函数-bound function-BF,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。)
const hero = {
heroName: "Batman",
dialogue() {
console.log(`I am ${this.heroName}`);
}
};
setTimeOut(hero.dialogue.bind(hero), 1000);
使用 call或 apply方法也无法改变 this的值 。
箭头函数中的“this”
箭头函数引用的是箭头函数在创建时设置的 this值,不是执行时环境this。
箭头函数会永久地捕获 this值,阻止 apply或 call后续更改它。
为了解释箭头函数中的 this是如何工作的,我们来写一个箭头函数:
const batman = this;
const bruce = () => {
console.log(this === batman);//true
};
bruce();
(译者注:箭头函数中没有this绑定,必须通过查找作用域链来决定它的值,如果箭头函数被非箭头函数包裹,那么this值由外围最近一层非箭头函数决定,否则为undefined。)
箭头函数也不能用作构造函数。因此,我们也不能在箭头函数内给 this设置属性。
那么箭头函数对 this 可以做什么呢?
箭头函数可以使我们在回调函数中访问 this 。
const counter = {
count: 0,
increase() {
setInterval(function() {
console.log(++this.count);
//只会得到一个 NaN的列表。这是因为 this.count已经不是指向 counter对象了。
//它实际上指向的为 global对象。
}, 1000);
}
}
counter.increase();
//使用箭头函数
const counter = {
count: 0,
increase () {
setInterval (() => {
console.log (++this.count);
}, 1000);
},
};
counter.increase();
Class中的“this”
类通常包含一个 constructor , this可以指向任何新创建的对象。
不过在作为方法时,如果该方法作为普通函数被调用, this也可以指向任何其他值。与方法一样,类也可能失去对接收器的跟踪。
class Hero {
constructor(heroName) {
this.heroName = heroName;
}
dialogue() {
console.log(`I am ${this.heroName}`)
}
}
const batman = new Hero("Batman");
batman.dialogue();
构造函数里的 this指向新创建的 类实例。当我们调用 batman.dialogue()时, dialogue()作为方法被调用, batman是它的接收器。
但是如果我们将 dialogue()方法的引用存储起来,并稍后将其作为函数调用,我们会丢失该方法的接收器,此时 this参数指向 undefined 。
const say = batman.dialogue;
say();
出现错误的原因是JavaScript 类是隐式的运行在严格模式下的。我们是在没有任何自动绑定的情况下调用 say()函数的。要解决这个问题,我们需要手动使用 bind()将 dialogue()函数与 batman绑定在一起。
const say = batman.dialogue.bind(batman);
say();
我们也可以在 构造函数方法中做这个绑定。
网友评论