【问题标题】:JavaScript ecma6 change normal function to arrow functionJavaScript ecma6 将普通函数更改为箭头函数
【发布时间】:2015-11-05 16:27:25
【问题描述】:

我有那个代码:

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,我不知道怎么改。

My fiddle

【问题讨论】:

    标签: javascript ecmascript-6 arrow-functions


    【解决方案1】:

    你不能。这是不可能的。箭头函数中的this 是词法范围的,这是它们的突出特点。但是您需要动态绑定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);
    

    【讨论】:

    • 感谢您的快速回复。
    • 第二个代码很完美——这正是我所需要的,非常感谢。
    猜你喜欢
    • 2019-04-12
    • 2022-12-06
    • 2017-03-13
    • 2020-05-07
    • 1970-01-01
    • 2019-02-24
    • 2019-01-17
    • 2015-11-03
    相关资源
    最近更新 更多