4 ms·
No, prototypes are a wrong idea. They are both complex and dangerous. Complex because you have to add methods indirectly and yet there are no classes (I mean, s
by gabordemooij 15y ago
No, prototypes are a wrong idea. They are both complex and dangerous. Complex because you have to add methods indirectly and yet there are no classes (I mean, seriously... how can anyone claim this makes sense?). Dangerous because you can easily break native functions like toString().
- stephenr 15y agoYou can override the tostring method on any object. You can override any method on any object - JS is a dynamic language, not using new & prototypes won't change that.
- gabordemooij 15y agoThis is not true. With prototypes you can override default functionality thus introducing unexpected behaviours. While you can indeed override individual instance methods with augmentation, you cannot override the 'general' toString() function. str = 'a'; str.toString = null str.toString(); //still works str = new String(); str.toString = null; str.toString(); //fails str2 = new String(); str.toString(); //still works but: String.prototype.toString = null; str = new String(); str.toString(); //unexpected error
- russfrank 15y agoThat's because "override the 'general' toString() function" doesn't make sense. This is a method. It must be overriden for a particular class of objects. The first part of your example is due to the conversion between primitives and objects for method calls. It has little to do with prototypal inheritance. Then, you override the method on an instance of String. When you set toString to null, of course, the call to toString fails. Lastly, you override it on the prototype of String, which will apply to all String objects. Why is this an unexpected error? toString is on the prototype, because it's defined on the class, not the instance. I'm not sure what the confusion is here.
- stephenr 15y agoYou're suggesting that the ability to provide a "toString" method on a custom object type (aka "Class") is a bad thing, because if you set it to NULL, it will fail when called? Seriously? By your logic, cars are bad because if you run a pipe from the exhaust to the inside of the car and sit in it with the engine running, it will kill you. Any developer can do stupid things in any language, with any code pattern, and trying to use that as a reason not to take advantage of a language's features is ridiculous.