JS设计模式---1. 富有表现力的JS
2018-12-07 本文已影响16人
念丶凉
前言: 最近准备把js设计模式这本书看一遍,然后也就是把书上的例子什么的挑挑拣拣做个记录。刚开始一些设计模式可能理解的不够深入,有些地方写的不是很到位,以后有更深的理解再回来补充。
创建可被链式调用的类
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();
创建匿名函数 (闭包)
var baz;
(() => {
var foo =10;
var bar = 2;
baz = ()=>{
return foo * bar
}
})()
baz() // 20
因为baz函数定义在闭包内 所以它可以访问到foo和bar两个变量 即使是在闭包执行结束后
对象的易变性
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的私有方法,并不存在于原型上