Skip to content Skip to sidebar Skip to footer

Javascript Ecma6 Change Normal Function To Arrow Function

I have that code: function defineProperty(object, name, callback){ if(object.prototype){ Object.defineProperty(object.prototype, name, {'get': callback}); } } defin

Solution 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:

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

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

functiondefineProperty(object, name, callback) {
    if (object.prototype)
        Object.defineProperty(object.prototype, name, {
            get(){ returncallback(this); }, // dynamic thisconfigurable: true
        });
}
defineProperty(String, "isEmpty", self => self.length === 0);

Post a Comment for "Javascript Ecma6 Change Normal Function To Arrow Function"