ecmascript 6 - JavaScript ecma6 change normal function to arrow function - Stack Overflow

I have that code:function defineProperty(object, name, callback){if(object.prototype){Object.defineProp

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

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

Share Improve this question edited Aug 12, 2015 at 21:47 Bergi 667k161 gold badges1k silver badges1.5k bronze badges asked Aug 12, 2015 at 21:31 s77ss77s 3141 gold badge2 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745137491a4613273.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信