Home >Web Front-end >JS Tutorial >How to define a class in JavaScript_Basic knowledge
This is how I originally wrote it:
function Dog(){ this.name = 'hachi'; } Dog.prototype = { makeNoise:function(){ alert('wangwangwang'); } };
Later I saw another way of writing that was a little more complicated and seemed unnecessary:
function Dog(){ var privateVariable = 'secret'; var fn = function(){ //... } fn.prototype = { makeNoise:function(){ alert('wangwangwang'); } } return fn; }
The Dog function here is actually a class-making function, which returns the real Dog class.
I feel that the advantage of doing this is better encapsulation.
For example, privateVariable here is a private variable:
var d = new Dog; d.privateVariable //undefined
In addition, if you add a sentence at the end of the first example:
Dog.prototype = { //e...WTF?? }
This way Dog is no longer Dog~
Later understanding:
The above method of creating a new class directly overrides the prototype object. In this way, the original built-in attributes of the prototype are gone (arguments, call, apply, etc.).
The following method of creating a new class seems better:
var Dog = function(name){ this.name = name; var privateVariable = 'you cannot see me.'; this.getPrivate = function(){return privateVariable;}; }