In JS, creating objects (create object) is not exactly what we often say to create class objects, JS objects are emphasized is a composite type, JS to create objects and access to objects is extremely flexible.
JS object is a composite type, which allows you to store and access through variable names, in another way, an object is an unordered set of attributes, each of which is made up of names and values (does it sound like a hash table, dictionary, health/value pair that we've often heard about?) , where the value type may be a built-in type (such as number,string) or an object.
Enclosed by a pair of curly braces
Copy Code code as follows:
var emptyobj = {};
var myobj =
{
' ID ': 1,//property name enclosed in quotes, attributes separated by commas
' Name ': ' MyName '
};
var m = new MyObj (); does not support
I don't know if you notice that objects are declared with Var, like the above code, just simply declare an object, it has only one copy, you can't use the new operation like an instantiated class object, like the annotation section of the code above. This greatly restricts the reuse of objects, unless you create objects that require only one copy, otherwise consider creating objects in other ways.
Let's look at how to access the object's properties and methods.
Copy Code code as follows:
var myobj =
{
' ID ': 1,
' Fun ': function () {
Document.writeln (this.id + '-' + this.name);//Access in "object. Properties" mode
},
' Name ': ' MyObj ',
' Fun1 ': function () {
Document.writeln (this[' id '] + ' + ' + this[' name ');//Access by collection
}
};
Myobj.fun ();
Myobj.fun1 ();
Results
1-myobj 1+myobj
second, using function keyword simulation class
Use this in function to refer to the current object, declaring the property by assigning it to the property. If you declare a variable with VAR, the variable is a local variable and is only allowed to be called in the class definition.
Copy Code code as follows:
function MyClass () {
This.id = 5;
this.name = ' MyClass ';
This.getname = function () {
return this.name;
}
}
var my = new MyClass ();
alert (my.id);
Alert (My.getname ());
Results
5
MyClass
create an object in the function body, declare its properties, and return
Creating an object in a function body can take advantage of the 1th method, or the new object () first; Assign values to each property.
However, objects created in this way do not have a smart hint in the VS2008 SP1.
Copy Code code as follows:
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);
Results
2
MyClass
1
_myclass