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 in quotation marks and separated by commas.
' Name ' : ' Myname '
};
// VaR M = new myobj (); // unsupported I wonder if you noticed that all objects are declared with VAR, as shown in the above Code It is just a simple declaration of an object. It has only one copy. You cannot use the new operation for it like an instantiated class object, just like the comments of the above Code. 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 ); // Access by "object. Attribute"
},
' Name ' : ' Myobj ' ,
' Fun1 ' : Function (){
Document. writeln ( This [ ' ID ' ] + ' + ' + This [ ' Name ' ]); // Access in collections
}
};
Myobj. Fun ();
Myobj. fun1 ();
// Result
// 1-myobj 1 + myobj
Ii. simulate a class with the function keyword Use 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 return You 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