1.this的指向
this的指向在没有call, apply,bind的修改之下,遵循谁调用我,我指向谁的这个规则
window.identity = 'The Window';
let object = {
identity: 'My Object',
getIdentityFunc() {
console.log(this.identity, '--调用1'); // My Object --调用1
}
};
object.getIdentityFunc()
getIdentityFunc()在这里是被object调用,所以this指向object,this.identity的key指向的也是object底下的属性identity的value-My Object
window.identity = 'The Window';
let object = {
identity: 'My Object',
getIdentityFunc() {
console.log(this.identity, '--调用1'); // My Object --调用1
return function() {
console.log(this.identity, '--调用2') // The Window --调用2
return this.identity
}
}
};
object.getIdentityFunc()()
不要晕,还是根据谁调用我,我指向谁的这个规则 object.getIdentityFunc()执行完页面就只剩了
function() {
console.log(this.identity, '--调用2')
return this.identity
}
object.getIdentityFunc()()相当于页面只有
(function() {
console.log(this.identity, '--调用2')
return this.identity
})()
如果全局作用域下只有一个匿名函数的调用,指向window
(function(){
console.log(this); // window
})()
所以调用2里面的this指向为window,也是获取window底下的属性this.identity为window
2. var that = this的使用
接上,如果我需要在匿名函数里面也拿到object的this.identity = 'My Object'怎么做
window.identity = 'The Window';
let object = {
identity: 'My Object',
getIdentityFunc() {
console.log(this.identity, '--调用1'); // My Object --调用1
var that = this
return function() {
console.log(that.identity, '--调用2') // My Object --调用2
return that.identity
}
}
};
object.getIdentityFunc()()
将匿名函数上一级的this存起来,然后在匿名函数里面调用
3. 箭头函数
箭头函数根本没有自己的this,导致内部的this就是外层代码块的this
意思就是箭头函数内部的this和外层代码的一致,于是改写一下
window.identity = 'The Window';
let object = {
identity: 'My Object',
getIdentityFunc() {
console.log(this.identity, '--调用1'); // My Object --调用1
return () =>{
console.log(this.identity, '--调用2') // My Object --调用2
return this.identity
}
}
};
object.getIdentityFunc()()
用了箭头函数,在2中的需求,可以告别this的赋值
4.我的公众号
前段时间情绪低迷,终于开启了很久就想写又没有写的公众号,主要是记录在前端行业中的摸爬滚打以及生活中真实趣事与感悟。技术虽菜,但是不能放弃,慢慢进步呀~
欢迎关注,一起唠嗑!
微信公众号:程序媛爱唠嗑