JS设计模式---1.富有表现力的JS

前言: 最近准备把 js 设计模式这本书看一遍,然后也就是把书上的例子什么的挑挑拣拣做个记录。刚开始一些设计模式可能理解的不够深入,有些地方写的不是很到位,以后有更深的理解再回来补充。

创建可被链式调用的类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 Function.prototype.method = function(name, fn) {
this.prototype[name] = fn; //原型
return this;
}
var Amin= function(){
...
}
Amin
.method('start',() => {
...
})
.method('stop',() => {
...
})
var a = new Amin(); //构造函数
a.start();
a.stop();

创建匿名函数 (闭包)

1
2
3
4
5
6
7
8
9
var baz;
(() => {
var foo =10;
var bar = 2;
baz = ()=>{
return foo * bar
}
})()
baz() // 20

因为 baz 函数定义在闭包内 所以它可以访问到 foo 和 bar 两个变量 即使是在闭包执行结束后

对象的易变性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
getName: function(){
return this.name;
},
getAge: function(){
return this.age;
}
}
var alice = new Person('Alice',30);
var bill = new Person('Bill',25);
Person.prototype.getGreeting = function(){
return 'Hi' + this.getName() + '!'
}
alice.displayGreeting = function(){
return this.getGreeting()
}
console.log(alice.getGreeting()) //HiAlice!
console.log(bill.getGreeting()) //HiBill!
console.log(alice.displayGreeting()) //HiAlice!
console.log(bill.displayGreeting()) //not a function

上面这个例子中,类的 getGreeting 方法定义在实例创建后,但是这两个实例依然可以获取到方法,原因在于 prototype 的工作机制。对象 alice 还得到了 displayGreeting 方法,而别的实例没有,是因为 displayGreeting 方法是 alice 的私有方法,并不存在于原型上