1. Create objects (one by one) with new Object()
Method: First use the object constructor to create an object, and then enrich the member information.
var person3 = new Object();
console.log(person3); //Object { }
var person4 = new Object();
person4.name = "newObject";
person4.age = 32;
console.log(person4) //Object { name: "newObject", age: 32, Introduce: Introduce()
person4.Introduce = function() {
console.log("My name is " + this.name + ".I'm " + this.age); //My name is newObject.I'm 32
};
person4.Introduce();
Copy the code
2. Create objects (one by one) using curly braces (object literals)
Method: Write member information to {} and assign a value to a variable, which is then an object.
- If {} is empty, an empty object is created:
- We can also enrich the object with member information.
- Object. Member name = value;
- Object [member name] = value;
Var person1 = {} // Create an empty object console.log(person1); Var person2 = {name: "object literal ", age: 32, Introduce: function() { console.log("My name is " + this.name + ".I'm " + this.age); }}; person2.worker = 'coding'; Console. log(person2); person2.Introduce();Copy the code
3. Use constructors to create objects
Methods: This is fundamentally different from creating objects from classes. This function is automatically executed when an object is created using this method.
Var obj = new ();
function Person5(name, age) { this.name = name; // Set the default member this.age = age with this keyword; this.Introduce = function() { console.log("My name is " + this.name + ".I'm " + this.age); }; }; Var person5 = new person5 (" constructor ", 11); person5.Introduce(); console.log(person5); Var person6 = new Person5(" constructor 1", 112); person6.Introduce(); console.log(person6); Var person7 = new Person5(" constructor 2", 113); person7.Introduce(); console.log(person7);Copy the code