Custom methods and usefulness of constructors and prototypes in web-dev

ok so I know prototype is used for inheritance and in combination with constructor function can be used to create custom methods. so my question is twofold here: how can I create methods for pre-built JavaScript objects like integers, strings, arrays, etc ...

Another question, besides my own methods, is the usefulness of constructors / prototypes in day to day web development (i.e. building websites), or even more so for high level development like building a web application or development using new technologies (i.e. html5 canvas or three.js), I have not seen anywhere on the Internet where this is used in an everyday situation.

+3


source to share


3 answers


To create a Javascript method for an already existing object, you can simply add it to your constructor prototype:

String.prototype.firstLetter = function() { return this.charAt(0); }
var myStr = "Cool str!";
alert(myStr.firstLetter()); // 'C'

      

As to how useful it is, depends on what you are doing with Javascript. If you are writing client side code and you need to modify an existing component, it might be useful to use a monkey patch there. If you need some structure in your code (and you do), creating an object to represent the state of an interface can be helpful.



Also, knowing how to use the tool usually avoids self-harm. =)

If you're interested, you can take a look at Crockford's page or buy his Javascript: The Good Parts.

There is a lot of confusion that you can avoid if you know the language, and you might even like it and learn that you can do a lot of useful things.

+1


source


You can add functions to the class prototype:

String.prototype.report_fish = function() { alert("a fish!"); };
"".report_fish();

      

You can do this with numbers as well, although the syntax for the call is slightly different:



Number.prototype.report_fish = function() { alert("a fish!"); };
(0).report_fish();

      

As to why you would do this, I personally believe that you should avoid doing this with inline objects where possible. (A persistent problem to deal with when building reusable Javascript libraries, and there are probably still people out there who tend to override and extend the prototype Object

.)

+1


source


Here's an example that expands the number:

Number.prototype.between = function(a, b) {
  return this >= a && this <= b
}
var num = 0;
if (num.between(0,0)) alert('is between')
else alert('not');

      

While I use prototype a lot, I have yet to come across a serious reason for using a constuctor property that returns the type of an object. W3schools.com has a good illustration of this property at http://www.w3schools.com/jsref/jsref_constructor_math.asp

+1


source







All Articles