2 回答

TA貢獻2051條經驗 獲得超10個贊
您可以嘗試這樣做:
Object.defineProperty(String.prototype, 'count', {
get: function() { return this.length; }
});
console.log(
"abc".count // 3
)
但我建議您避免在 JS 中擴展現有對象。你可以在這里閱讀更多關于它的信息

TA貢獻1807條經驗 獲得超9個贊
雖然我是 ES5 的粉絲,但 ES6 帶來的一件好事終于是代理了。你不必使用它們,但它們會給你很大的靈活性和一致性:
function convertToProxy(x){
x = Object(x);
let proxy = new Proxy(x,{
get: function(x,key,proxy){
switch (key) {
case "count":
return 3;
default:
return function(){
return "hmmmm"
};
}
},
getPrototypeOf: function(x){
return String.prototype;
}
});
return proxy;
}
let y = convertToProxy("abc");
y + "a" // "hmmmma"
y - 3 // NaN
y.count - 3 //0
添加回答
舉報