JavaScript ecma6将正常功能更改为箭头功能

s77*_*77s 5 javascript ecmascript-6 arrow-functions

我有那个代码:

function defineProperty(object, name, callback){
    if(object.prototype){
        Object.defineProperty(object.prototype, name, {"get": callback});
    }
}
defineProperty(String, "isEmpty", function(){return this.length === 0;});
Run Code Online (Sandbox Code Playgroud)

我用它如下:

console.log("".isEmpty, "abc".isEmpty);
Run Code Online (Sandbox Code Playgroud)

它返回:

true, false
Run Code Online (Sandbox Code Playgroud)

现在,我想将函数更改为以下内容:

defineProperty(String, "isEmptyWithArrow", () => this.length === 0);
Run Code Online (Sandbox Code Playgroud)

但"这个"指的是Window,我不知道如何改变它.

我的小提琴

Ber*_*rgi 7

你不能.这不可能.this在箭头函数是词法范围,这是他们的突出特点.但是你需要一个动态绑定this,这function就是有益的.

如果您坚持使用花哨的新ES6功能,请转到方法定义:

function defineProperty(object, name, descriptor) {
    if (object.prototype)
        Object.defineProperty(object.prototype, name, descriptor);
}
defineProperty(String, "isEmpty", {get(){return this.length === 0;}, configurable:true});
Run Code Online (Sandbox Code Playgroud)

当然,您也可以采用将实例作为参数的回调:

function defineProperty(object, name, callback) {
    if (object.prototype)
        Object.defineProperty(object.prototype, name, {
            get(){ return callback(this); }, // dynamic this
            configurable: true
        });
}
defineProperty(String, "isEmpty", self => self.length === 0);
Run Code Online (Sandbox Code Playgroud)