JavaScript as a weak type of speech, there is no similar to the concept of "class" in java,c#, but there are many times in the actual development of such requirements, there are now know that there are two ways to simulate.
1. By declaring an object, you can have the following code:
var people = { age:12, name: "Jack", Sex: "Male", setage:function (value) { this.age = value; }, getage:function () { return this.age; }, setname:function (value) { this.name = value; }, getname:function () { return this.name; }, setsex:function (value) { this.sex = value; } , getsex:function () { return this.sex; }, //There are other methods in addition to the read methods of these properties sayhi:function () { document.write ("hi,everybody!") ,}, //can also write function Sayhi () { document.write ("Hi, Everybody! "); } }
Such a "Class" is written, can be called by the following way:
People.age (or people.getage) to get age information
People.setage to modify the age
It is important to note that since "people" is not a real class, but rather an object of JavaScript, all elements in the people, whether attributes or methods, are treated as attributes by JavaScript, so they are all separated by ",".
2. By declaring a function
function people () { var age,name,sex; This.getage = function () { return this.age; } This.setage = function (value) { this.age = value; } }
The related operation is basically the same as the first method.
The application scenarios of the two methods are not clear at present and need further study.
How to emulate "class" in JavaScript