JS to create the custom class and create the object:
JS Creation class and As3,java are very different,,, below to see his flesh.
Since JS is also an object-oriented programming language, there are also the creation of custom classes like other languages, and the creation of objects through classes.
JS class is a three-sector composition
1. Constructor function
2. Properties
3. Methods
To customize a class:
function MyClass (id,age,name) { this.id = ID; This.age = age; THIS.name = name;}
From the definition of this class, it can be seen that the form of JS definition class and other languages are very different, other language definition classes need to formally define the class, and JS just use the function keyword to define a constructor. You can then use the New keyword to create an object:
var New MyClass (12,23,meimei);
From this class definition we can also see the difference between JS and other languages:
this. id = ID;
In fact, the ID of this variable we do not define. In other languages, you will be given an error. However, JS can automatically take the ID as a property, because JS does not need to define the properties of the class beforehand, just assign a value to the property, JS will customize the creation of these properties. Actually the object is also used. When assigning values to an object that is not defined beforehand, JS automatically creates these attributes.
This kind of freedom to create properties looks good, but it brings a lot of drawbacks, when we spell the existing attributes, if we accidentally misspelled, this will give the object a new attribute.
To prevent this from happening we can use set and get as in other languages:
functionMyClass (id,name) { This. ID =ID; This. Name =name; } MyClass.prototype.getId=function () { return This. ID; } MyClass.prototype.setId=function(ID) { This. ID =ID; } MyClass.prototype.getName=function () { return This. Name; } MyClass.prototype.setName=function(name) { This. Name =name; } varmy =NewMyClass (123, "Weizi"); document.write (My.getid ()); document.write (My.getname ()); My.setid (345); document.write (My.getid ());
The following is a concrete example:
<HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head><title>Title page</title><Scriptlanguage= "JavaScript"type= "Text/javascript"> functionMyClass (id,name) { This. ID=ID; This. Name=name; } MyClass.prototype.getId= function () { return This. ID; } MyClass.prototype.setId= function(ID) { This. ID=ID; } MyClass.prototype.getName= function () { return This. Name; } MyClass.prototype.setName= function(name) { This. Name=name; } varmy= NewMyClass (123,"Weizi"); document.write (My.getid ()); document.write (My.getname ()); My.setid (345); document.write (My.getid ());</Script></Head><Body> <PID= "my"></P></Body></HTML>
JS Custom Classes and objects