JavaScript ecma6将普通函数转换为箭头函数

8
我有这段代码:
function defineProperty(object, name, callback){
    if(object.prototype){
        Object.defineProperty(object.prototype, name, {"get": callback});
    }
}
defineProperty(String, "isEmpty", function(){return this.length === 0;});

我是这样使用它的:

console.log("".isEmpty, "abc".isEmpty);

并且它返回:

true, false

现在,我想把函数更改为以下内容:
defineProperty(String, "isEmptyWithArrow", () => this.length === 0);

但是 "this" 指的是 Window,我不知道如何改变它。

我的 fiddle

1个回答

9

你不能这样做,这是不可能的。箭头函数中的this是词法作用域,这是它们的杰出特点。但你需要一个动态绑定的this,这就是函数的优势所在。

如果你坚持使用新的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});

当然,你也可以使用一个回调函数,并将实例作为参数传递给它:
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);

感谢您的快速回复。 - s77s
1
第二段代码非常完美 - 这正是我需要的,非常感谢。 - s77s

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接