How to use JavaScript to define a class, javascript a class
My original method is as follows:
function Dog(){ this.name = 'hachi';}Dog.prototype = { makeNoise:function(){ alert('wangwangwang'); }};
Later, I saw another complicated and seemingly unnecessary statement:
function Dog(){ var privateVariable = 'secret'; var fn = function(){ //... } fn.prototype = { makeNoise:function(){ alert('wangwangwang'); } } return fn;}
Here, the Dog function is actually a manufacturing function, which returns the real Dog class.
I feel that the advantage of doing so is better encapsulation.
For example, privateVariable is a private variable:
var d = new Dog;d.privateVariable //undefined
In addition, if you add the following sentence at the end of the first example:
Dog.prototype = { //e...WTF??}
In this way, Dog is not a Dog ~
Later understanding:
The method for creating a new class directly overwrites the prototype object. In this way, prototype has no built-in attributes (arguments, call, apply, etc ).
The method for creating a class below seems better:
var Dog = function(name){ this.name = name; var privateVariable = 'you cannot see me.'; this.getPrivate = function(){return privateVariable;};}
How does javascript define a class, attribute, and method? Write a program
// Define the Person class
Function Person (){
This. name = "Test"; // name attribute
This. age = 16; // age attribute
This. sex = "female"; // gender attribute
This. getName = function (){
// Obtain the name
Return this. name;
}
This. getAge = function (){
// Obtain the age
Return this. age;
}
This. getSex = function (){
// Obtain the Gender
Return this. sex;
}
}
Use
Var p = new Person ();
Alert (p. getName ());
Alert (p. getAge ());
Alert (p. getSex ());
How to define a boolean attribute in javascript?
Var a = true;
If (){
...
}
Note that the quotation marks are strings.