Several methods for creating classes/objects in Javascript
Posted on lucasyang read (3426) Comments (2)
Edit favorites
In JS, the create object is not exactly the class object that we often call to create. The objects in JS emphasize a composite type, creating objects in JS and accessing objects are extremely flexible.
Javascript objects are a composite type that allows you to store and access them through variable names. In another way, an object is a disordered set of attributes, each item in the set is composed of names and values (does it sound like hash tables, dictionaries, and healthy/value pairs we often hear about ?), The value type may be a built-in type (such as number or string) or an object.
I. enclosed by a pair of braces
VaR emptyobj = {};
VaR myobj =
{
'Id': 1, // attribute names are enclosed by quotation marks, and attributes are separated by commas.
'Name': 'myname'
};
// Var M = new myobj (); // unsupported
I don't know if all objects are declared with var. Just like the above Code, it is just a simple declaration of an object, and it has only one copy, you cannot use the new operation on an object like an instantiated class object, as in the comments section of the Code above. In this way, the reuse of objects is greatly limited. Unless the object you create requires only one copy, other methods are used to create the object. The following describes how to access the attributes and methods of an object.
VaR myobj =
{
'Id': 1,
'Fun ': function (){
Document. writeln (this. ID + '-' + this. Name); // you can use the "object. Attribute" method to access
},
'Name': 'myobj ',
'Fun1': function (){
Document. writeln (this ['id'] + '+ this ['name']); // access data in a set
}
};
Myobj. Fun ();
Myobj. fun1 ();
// Result
// 1-myobj 1 + myobj
Ii. simulate a class with the function keywordUse this in function to reference the current object and declare the attribute by assigning values to the attribute. If VaR is used to declare a variable, the variable is a local variable and can only be called in the class definition.
Function myclass (){
This. ID = 5;
This. Name = 'myclass ';
This. getname = function (){
Return this. Name;
}
}
VaR my = new myclass ();
Alert (My. ID );
Alert (My. getname ());
// Result
// 5
// Myclass
3. Create an object in the function body, declare its attributes, and then returnYou can use the method of the first point to create an object in the function body, or use new object () to assign values to each attribute. However, the objects created in this way do not have smart prompts in vs2008 SP1.
Function myclass (){
VaR OBJ =
{
'Id': 2,
'Name': 'myclass'
};
Return OBJ;
}
Function _ myclass (){
VaR OBJ = new object ();
OBJ. ID = 1;
OBJ. Name = '_ myclass ';
Return OBJ;
}
VaR my = new myclass ();
VaR _ My = new _ myclass ();
Alert (My. ID );
Alert (My. Name );
Alert (_ My. ID );
Alert (_ My. Name );
// Result
// 2
// Myclass
// 1
// _ Myclass