Javascript 对象创建 | 天一阁

Javascript 对象创建

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
//JS里面创建一个对象最简单的方式是通过{}来直接建立
const bookLiteral = {
bookName : 'Program',
bookPrice : '30',
calcPrice : function(){}
};
//如果需要建立同类型的对象,可以用工厂,或者构造器
//factory function
function createBook(bookName, bookPrice) {
return {
bookName,
bookPrice,
calcPrice :function (numOfBooks){
return this.bookPrice * numOfBooks;
}
}
}
bookFromFactory = createBook("Factory Object", 15);
console.log(bookFromFactory);
console.log(bookFromFactory.calcPrice(30));
//constructor function
function Book(bookName, bookPrice){
this.bookName = bookName;
this.bookPrice = bookPrice;
this.calcPrice = function (numOfBooks){
return this.bookPrice * numOfBooks;
}
}
//js里的new 实际上先生成一个object,然后在这个object上,通过this, 动态增加属性和方法
myBook = new Book('JS', 10);
console.log(myBook.constructor);
for (let key in myBook){
console.log(key, myBook[key]);
}
const keys = Object.keys(myBook);
console.log(keys);
if ('bookPrice' in myBook) {
console.log('the price of 10 books: ', myBook.calcPrice(10));
}else
console.log('price of book:', myBook.calcPrice(1));
//js 的普通{} 都是对外直接访问的,这就导致无法真的做到oop,最起码的封装就没有
//所以需要通过曲线的方式来实现封装,比如:closur, getter , setter
function Circle(radius){
this.radius = radius;
//defaultLocation 外部是访问不到的,因为没有把这个defaultLocation加到this的属性上
let defaultLocation = {x:10, y:10};
this.draw = function (){
console.log('DefaultLocation:', defaultLocation);//这里用到了closure backpack
};
//getter setter
Object.defineProperty(this, 'defaultLocation', {
get: function(){
return defaultLocation;
},
set: function(value){
if (!value.x || !value.y){
throw new Error('Not Valid Value');
}
defaultLocation = value;
}
});
}
var circle = new Circle(10);
//circle.defaultLocation = {x:3}; 不符合合法性校验
circle.defaultLocation = {x:3, y:5};
console.log(circle.defaultLocation);