JavaScript ecma6将正常功能更改为箭头功能 [英] JavaScript ecma6 change normal function to arrow function
本文介绍了JavaScript ecma6将正常功能更改为箭头功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有代码:
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
现在,我想将功能更改为这个:
Now, I would like to change function to something like this:
defineProperty(String, "isEmptyWithArrow", () => this.length === 0);
但这个是指Window,我不知道如何更改它。
but "this" refers to Window and I do not know how to change it.
推荐答案
你不能。这不可能箭头功能中的这个
是词法的范围,这是他们的突出特点。但是,您需要动态绑定这个
,这就是函数
是有益的。
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 function
s are good for.
如果您坚持使用新颖的ES6功能,请执行方法定义:
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);
这篇关于JavaScript ecma6将正常功能更改为箭头功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文