In JS, creating an object (Create Object) is not exactly the creation of a class object as we often say. The object in JS emphasizes a composite type. Creating objects and accessing objects in JS is extremely flexible.
A JS object is a composite type that allows you to store and access it through variable names. To put it another way, an object is an unordered collection of properties. Each item in the collection is composed of a name and a value (doesn’t this sound weird? Like the HASH table, dictionary, key/value pair we often hear?), and the value type may be a built-in type (such as number, string), or an object.
1. Surrounded by a pair of curly brackets
Copy the code code as follows:
var emptyObj = {};
var myObj =
{
'id': 1, //Attribute names are enclosed in quotes and attributes are separated by commas
'name': 'myName'
};
//var m = new myObj(); //Not supported
I wonder if you have noticed that objects are all declared using var. Like the above code, it simply declares an object. It only has one copy. You cannot use the new operation on it like instantiating a class object. Like the above code Comments section. This greatly limits the reuse of objects. Unless the object you create only needs one copy, consider using other methods to create the object.
Let's take a look at how to access the properties and methods of an object.
Copy the code code as follows:
var myObj =
{
'id': 1,
'fun': function() {
document.writeln(this.id + '-' + this.name);//Access in "object.property" mode
},
'name': 'myObj',
'fun1': function() {
document.writeln(this['id'] + '+' + this['name']);//Access in collection mode
}
};
myObj.fun();
myObj.fun1();
// result
// 1-myObj 1+myObj
2. Use function keyword to simulate class
Use this in the function to refer to the current object, and declare properties by assigning values to them. If a variable is declared with var, the variable is a local variable and can only be called in the class definition.
Copy the 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());
// result
// 5
//myclass
3. Create an object in the function body, declare its properties and return
To create an object in the function body, you can use the method in the first point, or use new Object(); first and then assign values to each attribute.
However, objects created in this way do not have smart prompts in VS2008 SP1.
Copy the 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);
// result
// 2
//myclass
// 1
// _myclass