更多文章查看本专栏
闭包能够理解为'类生成器'
闭包代码:设计模式
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
而且全部的值都在this
能够使用将return的function写为一个私有的类,而且将外部的prototype写在里面,让闭包看起来更加的舒服,更像是一个总体。prototype
在使用类的时候可能会忘记使用new关键词。这个时候调用就像上面说的那种。执行一遍代码,而且其中的this指向window。设计
能够使用安全模式避免忘记使用new的状况。指针
列子:code
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 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);
这里就能够看出来若是原型链上的值为引用类型的时候会出现问题。
多继承的实现就是将父类们的全部属性进行拷贝到一个到当前类上。
当遇到引用类型的时候应当深拷贝,可是此处咱们只讨论浅拷贝的问题。
如下代码为多继承:
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; }
多态是对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]; } }