prototype 中 this的使用

我打算给 String 对象增加一个方法,用来对 字符串做一些处理。

String.prototype.asd = () => {
    console.log(this);
}

'aaa'.asd();

但是这个代码,打印的this , 是window对象。

如何做才能得到这个 对象本身 , 输出 aaa

阅读 3.2k
3 个回答

一个闭包看懂箭头函数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上

箭头函数的问题。别用箭头函数。

不要用 => 定义这个函数,
=> 函数中像普通的变量那样确定this 的值,而不是曾经的那一套。。。。。js 的 this 越来越复杂了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进