7

我有那个代码:

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,我不知道如何更改它。

我的小提琴

4

1 回答 1

9

你不能。这是不可能的。thisin 箭头函数是词法范围的,这是它们的突出特点。但是你需要一个动态绑定this,这就是functions 的好处。

如果你坚持使用花哨的 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);
于 2015-08-12T21:44:09.727 回答