JavaScript ecma6 change normal function to arrow function

血红的双手。 提交于 2019-12-23 11:57:57

问题


I have that code:

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

and I use it as below:

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

and it returns:

true, false

Now, I would like to change function to something like this:

defineProperty(String, "isEmptyWithArrow", () => this.length === 0);

but "this" refers to Window and I do not know how to change it.

My fiddle


回答1:


You cannot. This impossible. this in arrow functions is lexically scoped, that's their outstanding feature. But you need a dynamically bound this, and that's what functions are good for.

If you insist on using fancy new ES6 features, go for a method definition:

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

Of course, you could also take a callback that gets the instance as an argument:

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);


来源:https://stackoverflow.com/questions/31975772/javascript-ecma6-change-normal-function-to-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!