prototype 中 this的使用
本文介绍了prototype 中 this的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我打算给 String 对象增加一个方法,用来对 字符串做一些处理。
String.prototype.asd = () => {
console.log(this);
}
'aaa'.asd();
但是这个代码,打印的this , 是window对象。
如何做才能得到这个 对象本身 , 输出 aaa
解决方案
一个闭包看懂箭头函数this的三准则
准则一:箭头函数【本身的this】→<绑定>→【上下文的this】
function closure() {
let msg = closure.name;
return () => {//闭包箭头函数的this被绑定到上下文的closure函数的this上
console.log(`I'm in ${this.msg}`);
};
}
closure()(); //输出I'm in undefined,因为this指向window,window没有msg属性
准则二:箭头函数【本身的this】→<无法被>→call、apply、bind【改变】
closure().call({msg: 'obj'});
//输出I'm in undefined
// 因为call是对一个用箭头函数声明的闭包使用,而箭头函数【本身的this】是无法被改变的
准则三:箭头函数【上下文的this】→<可以被>→【改变】
closur.call({msg: 'obj'})();//注意call的位置与之前的不同
//输出I'm in obj,因为call是对箭头函数的上下文函数closure使用,this就被改变了
不应该使用箭头函数的场合举例:
let demo = document.querySelector('.demo');
demo.addEventListener('click', () => this.classList.add('change'););
//会导致this指向window而不是demo,这之类需要绑定this为当前对象的方法都不应使用箭头函数
String.prototype.asd = () => console.log(this);
//同理在构造函数,或在ES6的类Class中,原型prototype上的原型方法也不应使用箭头函数
应该使用箭头函数的场合举例:
function foo() {
setTimeout(function() {
console.log(`输出:${this.age}`);
// this指向window,foo函数的this改变时,它不会变
}, 0);
}
foo.call({ age: 998 });
setTimeout的特有特性:setTimeout内的this,与上下文函数foo的this,两者是分离的不相干的
所以修改为:
setTimeout(()=>{console.log(this.age)}) //此this就会被绑定到foo函数的this上
这篇关于prototype 中 this的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文