Search code examples
javascriptthisprototypeassigndefineproperty

Unable to assign to the value of `this` for a string prototype definition


Unable to assign to the value of this for a string prototype definition.

function testfunction(thisValue) {
    thisValue = thisValue || this;
    thisValue = "new test";
    console.log(thisValue);
    this = thisValue; // this throws error
}

Object.defineProperty(String.prototype, 'testfunction', { value: testfunction, enumerable: true });

let s = "i am a test"
s.testfunction()

for Array object I am using this.push. What is it for String to assign a new value.


Solution

  • It's certainly possible to add methods to the String prototype. Some people think that's terrible, but my feeling is that if you're careful and you understand the implications in general and for your specific universe, then it's not so bad. I'm not your dad so do what you want.

    That said, I would not make such methods enumerable, because that's one of the biggest problems with modifying standard prototypes. Also, for things like String, Number, and Boolean, you cannot modify the underlying primitive values because they're not mutable. When you invoke a method on a string primitive value, what's happening is that a wrapper object is instantiated for the purpose of evaluating the expression, and then that object is thrown away. Thus methods that compute some value from the base primitive string (or number or boolean) can do interesting things, but you can't modify those values.