创建对象的方式

总结创建对象的六种方式

new Object()、字面式

使用同一接口创建多个对象时,会产生大量重复代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var person = new Object();
person.name = "lisi";
person.age = 21;
person.family = ["lida","lier","wangwu"];
person.say = function(){
alert(this.name);
}

var person ={
name: "lisi",
age: 21,
family: ["lida","lier","wangwu"],
say: function(){
alert(this.name);
}
};

工厂模式

写一个方法,return new Object() 创建的对象

  • 解决了重复实例化多个对象的问题

  • 没有解决对象识别的问题,不知道对象是谁的实例

    因为全部都是Object,不像Date、Array等,本例中,得到的都是o对象,对象的类型都是Object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function createPerson(name,age,family) {
var o = new Object();
o.name = name;
o.age = age;
o.family = family;
o.say = function(){
alert(this.name);
}
return o;
}

var person1 = createPerson("lisi",21,["lida","lier","wangwu"]); //instanceof无法判断它是谁的实例,只能判断他是对象,构造函数都可以判断出
var person2 = createPerson("wangwu",18,["lida","lier","lisi"]);
console.log(person1 instanceof Object); //true

构造函数模式

  • 可以知道创建的对象是哪个的实例
  • 每个方法都会在每个实例上重新创建一遍,可能造成滥用闭包,内存泄漏的问题(如果方法引入了外部的变量)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Person(name,age,family) {
this.name = name;
this.age = age;
this.family = family;
this.say = function(){
alert(this.name);
}
}
var person1 = new Person("lisi",21,["lida","lier","wangwu"]);
var person2 = new Person("lisi",21,["lida","lier","lisi"]);
console.log(person1 instanceof Object); //true
console.log(person1 instanceof Person); //true
console.log(person2 instanceof Object); //true
console.log(person2 instanceof Person); //true
console.log(person1.constructor); //constructor 属性返回对创建此对象的数组、函数的引用

原型模式

  • 所有对象实例共享它的属性和方法
  • 可以设置实例自己的属性(方法)(即所谓的私有属性),可以覆盖原型对象上的同名属性(方法)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function Person() {
}

Person.prototype.name = "lisi";
Person.prototype.age = 21;
Person.prototype.family = ["lida","lier","wangwu"];
Person.prototype.say = function(){
alert(this.name);
};
console.log(Person.prototype); //Object{name: 'lisi', age: 21, family: Array[3]}

var person1 = new Person(); //创建一个实例person1
console.log(person1.name); //lisi

var person2 = new Person(); //创建实例person2
person2.name = "wangwu";
person2.family = ["lida","lier","lisi"];
console.log(person2); //Person {name: "wangwu", family: Array[3]}
// console.log(person2.prototype.name); //报错
console.log(person2.age); //21

混合模式(构造函数模式+原型模式)

构造函数模式用于定义实例属性,原型模式用于定义方法和共享的属性

混合模式共享着对相同方法的引用,又保证了每个实例有自己的私有属性。最大限度的节省了内存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Person(name,age,family){
this.name = name;
this.age = age;
this.family = family;
}

Person.prototype = {
constructor: Person, //每个函数都有prototype属性,指向该函数原型对象,原型对象都有constructor属性,这是一个指向prototype属性所在函数的指针
say: function(){
alert(this.name);
}
}

var person1 = new Person("lisi",21,["lida","lier","wangwu"]);
console.log(person1);
var person2 = new Person("wangwu",21,["lida","lier","lisi"]);
console.log(person2);