创建对象的多种方式

Factory

缺点:对象无法区分,所有的实例指向一个原型

1
2
3
4
5
6
7
8
9
10
11
12
13
function Person(name) {
let o = new Object()
o.name = name
o.getName = function () {
return this.name
}

return o
}

let person = new Person("Edward")
console.log(person instanceof Person) // false
console.log(person instanceof Object) // true

Constructor

缺点:每次创建实例时,每个方法需要被创建一次。

1
2
3
4
5
6
7
function Person(name) {
this.name = name
this.getName = function () {
// create function
return this.name
}
}

Prototype

缺点:

  1. 所有的属性和方法都共享
  2. 不能初始化值
1
2
3
4
5
6
7
8
function Person(name) {}
Person.prototype = {
constructor: Person,
name: "Edward",
getName: function () {
return this.name
},
}

Constructor & Prototype

1
2
3
4
5
6
7
8
9
10
function Person(name) {
this.name = name
}

Person.prototype = {
constructor: Person,
getName: function () {
return this.name
},
}

Safe constructor

没有公共属性,方法也不使用this对象,无法识别对象所属类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Person(name) {
let o = new Object()
o.name = name
o.getName = function () {
return name // formal parameter
}

return o
}

let person = new Person("Edward")
console.log(person.getName()) // Edward
person.name = "Jack"
console.log(person.getName()) // also Edward