Use the keyword new to create an object
Js code
Function Person (name, age) {this. name = name; this. age = age;} var p = new Person (); // You can also fill in initialization attributes, such as new Person ("lingceng", 22)
Directly create an Object using an Object
It can be seen that this method is very convenient to expand.
Js code
Var obj = new Object (); // var ={}; obj. name = "lingceng"; obj. age = 22;
Create with JSON (object literal description is more accurate, but JSON is better understood)
Starting with Javascript1.2, you can create an object more quickly.
Js code
Var p = {name: "lingceng", // "name": "lingceng is resolved in the same way as quotation marks. gender:" male "};
Practice
It is suitable for practice to create objects in combination with constructors and prototype modes.
Js code
Function Person (name, age) {// instance attributes // Copy this multiple times during the instance. name = name; this. age = age;} Person. prototype = {// http://developer.51cto.com/art/200907/134913.htm // The constructor property always points to the constructor that created the current object // because the prototype is replaced, you need to restore the construtor's default point to constructor: Person, showName: function () {alert ("ShowName in prototype:" + this. name) ;}, showAge: function () {alert (this. age) ;}} var p = new Person ("lingceng", 22); p. showAge (); // 22