你不能。这是不可能的。this
箭头函数是词法作用域的,这是它们的突出特点。但是你need动态绑定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);