简体   繁体   English

有没有办法在 JavaScript 中代理对属性的调用?

[英]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

You can try to do this:你可以尝试这样做:

 Object.defineProperty(String.prototype, 'count', { get: function() { return this.length; } }); console.log( "abc".count // 3 )

But I recommend you to avoid extending existing objects in JS.但我建议您避免在 JS 中扩展现有对象。 You can read more about it here你可以在这里阅读更多关于它的信息

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM