Domanda

Hey guys i have a question regarding prototype in javascript.

Which of the following is the correct and best way to use prototype and why?

var myClass = function(){
this.anotherFunction();
}

myClass.prototype.anotherFunction = function(){
  console.log('my prototype function');
}
var foo = new myClass(); // which automaticaly performs the function

OR

var myClass = function(){
}

myClass.prototype.anotherFunction = function(){
  console.log('my prototype function');
}
var foo = new myClass();
foo.anotherFunction(); // performs the function only when called

Thanks!

È stato utile?

Soluzione

The first implementation calls a method directly from the constructor. These methods are quite often some kind of initialization methods that build the needed inner state of the this context. In non JavaScript appropriate OOP speak this would mean that a method is called directly from your class constructor that builds up some initial state.

The second implementation exposes the prototype function anotherFunction as part of the public interface.

In short: Both variants are correct but implement different concepts

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top