-
Notifications
You must be signed in to change notification settings - Fork 0
/
chap2.js
169 lines (107 loc) · 2.8 KB
/
chap2.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
/**
* Created by Administrator on 2017/8/24 0024.
*/
//面向对象编程
//创建一个类
var Book = function(id,bookname,price){
this.id = id;
this.bookname = bookname;
this.price = price;
}
/*Book.prototype.display = function(){
}*/
Book.prototype = {
display : function(){
}
}
var book = new Book(10,"Javascript 设计模式",50);
console.log(book.bookname)
var Book1 = function(id,name,price){
var num = 1;
function checkId(){};
this.getName = function(){};
this.getPrice = function(){};
this.setName = function(){};
this.setPrice = function(){};
this.id = id;
this.copy = function(){}
this.setName(name);
this.setPrice(price);
}
Book.isChinese = true;
Book.resetTime = function(){
console.log('new Time')
}
Book1.prototype ={
isJSBook : false,
display : function(){}
}
var b = new Book1(11,"Javascript设计模式",40);
console.log(b.num)
console.log(b.isJSBook)
console.log(b.id)
console.log(b.isChinese)
//闭包的实现
var Book3 = (function(){
var bookNum = 0;
function checkBook(name){};
return function(newId,newName,newPrice){
var name,price;
function checkID(id){};
this.getName = function(){};
this.getPrice = function(){};
this.setName = function(){};
this.setPrice = function(){}
this.id = newId;
this.copy = function(){};
bookNum++;
if(bookNum > 100){
throw new Error("我们近出版100本书");
}
this.setName(name);
this.setPrice(price)
}
})()
Book3.prototype = {
isJSBook : false,
display : function(){}
}
//在闭包外部添加原型属性和方法看上去想似脱离了闭包这个类,所以有时在闭包内部实现一个完整的类,然后再将其返回
var Book = (function(){
var booknum = 0;
function checkBook(name){};
function _book(newId,newName,newPrice){
var name,price;
function checkID(id){};
this.getName = function(){};
this.getPrice = function(){};
this.setPrice = function(){};
this.setName = function(){}
this.id = newId;
this.copy = function(){};
booknum++;
if(booknum > 100){
throw new Error("我们仅出版100本书");
this.setName(name);
this.setPrice(price);
}
}
_book.prototype = {
isJSBook : false,
display : function(){}
}
return _book;
})()
//创建对象的安全模式
var Book = function(title,time,type){
if(this instanceof Book){
this.title = title;
this.time = time;
this.type = type;
}else{
return new Book(title,time,type)
}
}
var book = Book("Javascript","2012",'JS');
console.log(book.title)
console.log(book)