2

In the code snippet at http://jsfiddle.net/javascriptenlightenment/QvbDw/, the author augments the builtin String object constructor with 2 new properties - an array property and a function property.

I notice that for the new array property, he did this:

String.newArrayProperty = [];
// Q1: Why not String.prototype.newArrayProperty = []; ?

But for the new function property, he did this:

String.prototype.newFunctionProperty = function() {...};
// Q2: Why not String.newFunctionProperty = function() {...}; ?

What's the difference between String.newProperty and String.prototype.newProperty?

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
RBR
  • 999
  • 3
  • 13
  • 24

3 Answers3

5

String.newProperty adds a new propery to the String native function, but that property is in no way inherited by the strings it generates, while String.prototype.newProperty adds that new property to all the strings it generates, but not to the native function itself.

Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
2

String.property just ads the propery to String class as to an object, String.prototype.property adds this property to all instances of this class.

function F() {
}

F.p1 = function () { console.log('F.p1'); } ;
F.prototype.p2 = function () { console.log('F.prototype.p2'); } ;

F.p1(); // 'F.p1'
F.p2(); // error
new F().p1(); // error
new F().p2(); // 'F.prototype.p2'

Also look at:

  1. How does JavaScript .prototype work?
  2. http://www.w3schools.com/jsref/jsref_prototype_math.asp
  3. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype
Community
  • 1
  • 1
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

A method, assigned to the prototype of String can be applied to all instances of String. A method assigned to the String constructor has to be called as a static method with a string as parameter. If the method is in the prototype, within it, this refers to the string instance.

So:

String.prototype.insertLineNr = function(nr){return (nr||1) + ': ' +this;};
//                                                                  ^instance
String.insertLineNo = function(str,nr){return (nr||1) + ': ' +str;};
var str = 'Some line to be numbered';
//apply to instance
console.log(str.insertLineNr(5);        //=> '5: Some line to be numbered'
//can't apply direct String method to instance 
console.log(str.insertLineNo(str,5));   //=> TypeError
//Run String method 
console.log(String.insertLineNo(str,5); //=> '5: Some line to be numbered'

If the method name is equal, you can have the best of both worlds:

function insrtNr(str,nr){ return (nr||1) + ': ' + str || this;};
String.insertLineNr = insrtNr;
String.prototype.insertLineNr = insrtNr;
KooiInc
  • 119,216
  • 31
  • 141
  • 177