How do I define a class in JavaScript
- 2020-03-30 03:55:20
- OfStack
The way I used to write it was this:
function Dog(){
this.name = 'hachi';
}
Dog.prototype = {
makeNoise:function(){
alert('wangwangwang');
}
};
Then I saw another slightly more complicated and seemingly unnecessary way to write it:
function Dog(){
var privateVariable = 'secret';
var fn = function(){
//...
}
fn.prototype = {
makeNoise:function(){
alert('wangwangwang');
}
}
return fn;
}
The Dog function here is actually a manufacturing class function that returns the real Dog class.
It feels like the benefit of doing this is better encapsulation.
For example, privateVariable is a privateVariable:
var d = new Dog;
d.privateVariable //undefined
In addition, if I add a sentence at the end of the first example:
Dog.prototype = {
//e...WTF??
}
So a Dog is not a Dog
Later understanding:
This new class method overrides the prototype object directly. Then prototype's built-in properties (arguments, call, apply, etc.) are gone.
The following method of creating new classes seems better:
var Dog = function(name){
this.name = name;
var privateVariable = 'you cannot see me.';
this.getPrivate = function(){return privateVariable;};
}