sandrina-p
sandrina-p

Reputation: 4160

What is the difference between inherited method (prototype) and static method (expression)?

I have these two examples of functions on a string that do exactly the same:

//ex1 - inherited method
String.prototype.slugLower = function() {
    return this.split(' ').join('-').toLowerCase();
}

"hello World".slugLower();


//ex2 - static method
String.slugLower = function(str) {
    return str.split(' ').join('-').toLowerCase();
}

String.slugLower("hello World");

Both will return "hello-world". What is the difference between them? I mean performance / best practices.

Thanks

Upvotes: 1

Views: 83

Answers (3)

Steeve Pitis
Steeve Pitis

Reputation: 4443

Method defined in prototype will be available in all Object. For the most of use cases, 'your object'.protoype will be the best practice.

Another example :

var myObject = function monObject() {
   /*...*/ 

   this.function1 = function function1() {
      /*...*/ 
   };
};

myObject.prototype.function2 = function function2() {
  /*...*/ 
};

Then if you create 2 objects

var obj1 = new myObject();
var obj2 = new myObject();

Then you have this :

obj1.function1 !== obj2.function1

but :

obj1.function2 === obj2.function2

function1() is re create on every new myObject. Is it clear ?

Upvotes: 2

Byron
Byron

Reputation: 56

The best practice is define a function to do this

function slugLower(str){
     return str.split(' ').join('-').toLowerCase();
}

Both your examples will change the String object, there is some side effects, the first example is instance method, the second one is static function

Upvotes: 0

Amadan
Amadan

Reputation: 198324

The first is a method attached to a prototype. The second is a method attached to the String object. In a classical OO language, they would be called "inherited method" and "static method", respectively.

The performance difference is minuscule, and really shouldn't matter here. What should is: if you think a method is a behaviour of every object in a class of objects, it should be a prototypal (inherited) method. If you think it should be a behaviour that is related to multiple objects of the class or the class itself, you should use the second pattern. For example, "pee on" or "bark this loudly" is a behaviour of each dog: Dog.prototype.peeOn, Dog.prototype.barkWithVolume; "how many dogs in the world?" or "make a new dog" is not a behaviour of each dog, but of "doghood" and a pair of dogs, respectively: Dog.census and Dog.spawnPuppy.

Upvotes: 3

Related Questions