Implementation of the prototype method

If I implemented the x method in a string, for example:

String.prototype.x = function (a) {...} 

And then the new version of javascript actually implements the x method, but in a different way, returning something other than my implementation or function, with more / less arguments than my implementation. Will this violate my implementation and cancel it?

+6
source share
4 answers

No, you will redefine the default implementation of the specified function, starting from the point at which you declared / defined it. A "new" implementation will act in its own behavior until your implementation is defined.

 var foo = 'some arbitrary string'; console.log(foo.indexOf('s')); // logs [0] String.prototype.indexOf = function(foo, bar) { return 'foo'; }; console.log(foo.indexOf()); // logs [foo] 

Illustration: http://jsfiddle.net/Z4Fq9/

+2
source

You overwrite the standard implementation.

Any code using it will use yours instead.

Extension methods were proposed, and it was rejected because it was too expensive to implement in JS machines. They are talking about a new proposal (protocols) to solve the problem. ES6 characters will also help you with this (but with ugly syntax).

However, this is not a blow - this is a funny fact that no one will talk about.

No one is going to implement a method called x on String.prototype

You can realize it and get rid of it. Seriously, prollyfilling and polyfilling is a viable, expressive and interesting solution for many use cases. If you are not writing a library, I find it acceptable.

+3
source

Your code will override the default implementation.

However, if the interface of your method is incompatible with the standard, the libraries that you can use may depend on the standard behavior, so the program as a whole may break in any case with newer versions of the libraries.

All in all, this is a bad idea that does something that might break if others do the same: what if another library considers it a good idea to add the x method to the prototype of a standard string object? Trying to avoid conflicts is mandatory for libraries, but it is also good for applications (and if the application is written beautifully, then a lot of its code is probably very similar to a library and can develop in a library later).

This type of “fix” makes sense only to provide a standard method for broken or old javascript implementations where this method is missing. Fixing standard prototypes just because you can is a bad idea will make your code a bad neighbor that makes it difficult to share a page.

+1
source

If the implementation of x is a new version of Javascript, it is part of the kernel, so when you write String.prototype.x... it will already be there and you will overwrite it.

The best practice in such things is recording

 if( !String.prototype.x ){ String.prototype.x = function ... //your 
0
source

Source: https://habr.com/ru/post/958030/


All Articles