《JavaScript设计模式》阅读笔记_part1

0次阅读

共计 1695 个字符,预计需要花费 5 分钟才能阅读完成。

JavaScript 设计模式阅读
第二章:类
1、闭包实现类
闭包可以理解为 ’ 类生成器 ’
闭包代码:
var Book = (function(){
var bookNum = 0;
function checkBook(name){
}
return function(newId,newName,newPrice){
var name,price;
this.id = newId;
bookNum++;
if(bookNum > 100){
throw new Error(‘ 最多只出版 100 本书 ’);
}
function checkID(id){}
this.getName = function(){
console.log(name);
return name;
};
this.getPrice = function(){
console.log(price);
return price;
};
this.setName = function (mName) {
name = mName;
};
this.setPrice = function (mPrice) {
price = mPrice;
};
this.copy = function () {};
// 构造器
this.setName(newName);
this.setPrice(newPrice);
}
})();
Book.prototype = {
isJSBook: false,
display: function () {
}
}
使用:
var myBook = new Book(‘id’,’name’,’price’);
使用方法与普通的是一致的。但是如果不加 new 关键词的话
var myBook = Book(‘id’,’name’,’price’);
当不使用 new 关键词的时候只会将 Book 执行一遍并且 this 指针为 window 并且所有的值都在
可以使用将 return 的 function 写为一个私有的类,并且将外部的 prototype 写在里面,让闭包看起来更加的舒服,更像是一个整体。
2、对象的安全模式
在使用类的时候可能会忘记使用 new 关键词。这个时候调用就像上面说的那种。执行一遍代码,并且其中的 this 指向 window。
可以使用安全模式避免忘记使用 new 的情况。
列子:
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);
}
}
本质可以看出就是加了一层判断。
3、js 原型链对引用类型的无力。
当原型链上的值为引用的时候:
var test = function () {
}
test.prototype.nums = [1,2,3,4];
ins1 = new test();
ins2 = new test();
console.log(ins2.nums);
ins1.nums.push(5);
console.log(ins2.nums);
这里就可以看出来如果原型链上的值为引用类型的时候会出现问题。
4、多继承
多继承的实现就是将父类们的所有属性进行拷贝到一个到当前类上。当遇到引用类型的时候应当深拷贝,但是此处我们只讨论浅拷贝的问题。以下代码为多继承:
var mix = function () {
var len = arguments.length;
var target = arguments[1];
var arg;
for(var i = 1;i < len;i++){
arg = arguments[i];
for(var property in arg){
target[property] = arg[property];
}
}
return arg;
}
5、多态
多态是对 arguments 里面的值得个数进行统计,根据不同的情况给予不同的回应。简单例子
var add = function () {
var len = arguments.length;
switch (len) {
case 0:
return 10;
case 1:
return 10 + arguments[0];
case 2:
return arguments[0] + arguments[1];
}
}

正文完
 0