JS面向对象

几种创建对象的方向

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
* JS 面向对象,ECMAScript中有两种属性: 数据属性和访问器属性。
*/

"use strict";

// 1. 对象字面量
var person = {
name: 'HandsomeHan',
age: 23,
job: 'front-end-engineer',

sayName: function () {
console.log(this.name);
}
}

Object.defineProperty(person, "name", {
writable: false,
value: 'Handsome'
})

person.name = 'han'

console.log(person);

var book = {
_year: 2004,
edition: 1
}

Object.defineProperty(book, 'year', {
get: function () {
return this._year;
},
set: function (value) {
if (value > 2004) {
this._year = value;
this.edition += value - 2004;
}
}
});

book._year = 2006;
console.log(book.edition);

// 2. 工厂模式
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
console.log(o.name);
}
return o;
}

var person1 = createPerson('han', 23, 'front-end-engineer');

// 3. 构造函数模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function () {
console.log(this.name);
}
}

var person2 = new Person('han', 23, 'front-end-engineer');
var person3 = new Person('zhang', 24, 'front-end-enginner');

console.log(person2.constructor);
console.log(person3.constructor);

// 4. 原型模式
function Person() { }

Person.prototype.name = 'han';
Person.prototype.age = 29;
Person.prototype.job = 'front-end-engineer';
Person.prototype.sayName = function () {
console.log(this.name);
}

// 5. 组合使用构造函数模式和原型模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}

Person.prototype = {
constructor: Person,
sayName: function () {
console.log(this.name);
}
}

// 6. 动态原型模式

function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;

if (typeof this.sayName != 'function') {
Person.prototype.sayName = function () {
console.log(this.name);
}
}
}

// 7. 寄生构造函数模式
function Person(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
console.log(o.name);
}
return o;
}

var person4 = new Person('han', 23, 'front-end-engineer');