Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing prototype method

Tags:

javascript

If I implemented a method x on a String like :

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

And then the new version of javascript actually implements the x method, but on the another way, either returning something different than my implementation or function with more/less arguments than my implementation. Will this break my implementation and override it?

like image 829
London Avatar asked Nov 13 '13 22:11

London


2 Answers

You'll overwrite the default implementation.

Any code that uses it will use yours instead.

There was a proposal for scoped extension methods and it was rejected because it was too expensive computationally to implement in JS engines. There is talk about a new proposal (protocols) to address the issue. ES6 symbols will also give you a way around that (but with ugly syntax).

However, that's not the punch - here's a fun fact no one is going to tell you.

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

You can implement it and get away with it. Seriously, prollyfilling and polyfilling is a viable, expressive and interesting solution to many use cases. If you're not writing a library I think it's acceptable.

like image 82
Benjamin Gruenbaum Avatar answered Oct 17 '22 05:10

Benjamin Gruenbaum


No, you'll be overriding the default implementation of said function, from the point at which you've declared/defined it. The "new" implementation will function in its native behavior, until your implementation's 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/

like image 24
Alex Avatar answered Oct 17 '22 04:10

Alex