1.利用new Object()创建对象 (一个一个创建)
方法:先通过object构造器new一个对象,再往里丰富成员信息。
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();
2.利用花括号即对象字面量创建对象(一个一个创建)
方法:将成员信息写到{}中,并赋值给一个变量,此时这个变量就是一个对象。
- 如果{}中为空,则将创建一个空对象:
- 我们还可以给对象丰富成员信息。
- 对象.成员名称 = 值;
- 对象[成员名称] = 值;
var person1 = {} //创建空对象
console.log(person1);
var person2 = {
name: "对象字面量",
age: 32,
Introduce: function() {
console.log("My name is " + this.name + ".I'm " + this.age);
}
};
person2.worker = 'coding'; //丰富成员信息
console.log(person2);
person2.Introduce();
3.利用构造函数创建对象
方法:这与通过类创建对象有本质的区别。通过该方法创建对象时,会自动执行该函数。
var obj = new 函数名();
function Person5(name, age) {
this.name = name; //通过this关键字设置默认成员
this.age = age;
this.Introduce = function() {
console.log("My name is " + this.name + ".I'm " + this.age);
};
};
var person5 = new Person5("构造函数", 11);
person5.Introduce();
console.log(person5);
var person6 = new Person5("构造函数1", 112);
person6.Introduce();
console.log(person6);
var person7 = new Person5("构造函数2", 113);
person7.Introduce();
console.log(person7);