Here’s the code I’m working with at the moment:
Object.defineProperty(String.prototype, "testy", {
get: function() {
return this.string;
},
set: function(string) {
this.string = string;
}
});
console.log("tessfef3t".testy());
Before I would’ve used String.prototype.testy = function {}, however I’ve been told that using something similar to the the code above is the better way to do it. I’m not sure how that is meant to work but I haven’t got that code to work yet.
Could someone show me how to correctly do what I’m doing?
Thanks
testyis kind of a “fake” property — it has no value of its own, but setting or getting its value will invoke itssetandgetfunctions. You can use it like:EDIT:
Now I see your comment about what you actually want to happen. It’s not possible to alter the value of a string object, because strings are immutable. You’d have to destroy the string object and replace it with a new one, which is not possible within the object’s own member function.