[英]Is there a way to proxy a call to property in JavaScript?
I want to add a count property to string in JavaScript which calls the length property internally.我想在 JavaScript 中向 string 添加一个 count 属性,该属性在内部调用 length 属性。 I don't want to add it as a function.
我不想将其添加为函数。 How to do this?
这该怎么做?
"abc".count; // 3
Although I'm a fan of ES5, one good thing ES6 has brought are finally the proxies.虽然我是 ES5 的粉丝,但 ES6 带来的一件好事终于是代理。 You don't have to use them, but they will grant you a lot of flexibility and consistency:
您不必使用它们,但它们会给您带来很大的灵活性和一致性:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.