1

I want to add a count property to string in JavaScript which calls the length property internally. I don't want to add it as a function. How to do this?

"abc".count;  // 3
John Doe
  • 2,225
  • 6
  • 16
  • 44

2 Answers2

5

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. You can read more about it here

Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
1

Although I'm a fan of ES5, one good thing ES6 has brought are finally the proxies. 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
ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22