JavaScript ecma6 将普通函数更改为箭头函数
JavaScript ecma6 change normal function to arrow function
我有那个代码:
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);
它 returns:
true, false
现在,我想把函数改成这样:
defineProperty(String, "isEmptyWithArrow", () => this.length === 0);
但是"this"指的是Window,我不知道怎么改。
你不能。这不可能。箭头函数中的 this
是词法范围的,这是它们的突出特点。但是您 需要 一个动态绑定 this
,这就是 function
的好处。
如果您坚持使用新奇的 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);
我有那个代码:
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);
它 returns:
true, false
现在,我想把函数改成这样:
defineProperty(String, "isEmptyWithArrow", () => this.length === 0);
但是"this"指的是Window,我不知道怎么改。
你不能。这不可能。箭头函数中的 this
是词法范围的,这是它们的突出特点。但是您 需要 一个动态绑定 this
,这就是 function
的好处。
如果您坚持使用新奇的 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);