My original writing style is like this:
function Dog(){ this.name = 'hachi';}Dog.prototype = { makeNoise:function(){ alert('wangwangwang'); }};Later I saw another more complicated and seemingly unnecessary writing method:
function Dog(){ var privateVariable = 'secret'; var fn = function(){ //... } fn.prototype = { makeNoise:function(){ alert('wangwangwang'); } } return fn;}The Dog function here is actually a function that manufactures classes, which returns the real Dog class.
I feel that the benefit of doing this is to implement the encapsulation better.
For example, the privateVariable here is a private variable:
var d = new Dog;d.privateVariable //undefined
Also, if you add a sentence at the end of the first example:
Dog.prototype = { //e...WTF??}Dog is not Dog this way
Later understanding:
The above method of creating a new class directly rewrites the prototype object. In this way, the built-in properties of prototype will be gone (arguments, call, apply, etc.).
The following method of creating a new class seems to be better:
var Dog = function(name){ this.name = name; var privateVariable = 'you cannot see me.'; this.getPrivate = function(){return privateVariable;};}