Created
          March 8, 2014 10:07 
        
      - 
      
 - 
        
Save cuing/9428221 to your computer and use it in GitHub Desktop.  
    JavaScript Patterns
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // 类继承模式 uber 存储超类 | |
| function inherit(C, P) { | |
| var F = function(){}; | |
| F.prototype = P.prototype; | |
| C.prototype = new F(); | |
| C.uber = P.prototype; | |
| C.prototype.constructor = C; | |
| } | |
| // 一个常见的优化是避免在每次需要继承时都创建临时(代理)构造 | |
| // 函数。在具体实现上可以使用即时函数,并且在闭包中存储代理函数。 | |
| function inherit(C, P) { | |
| var F = function(){}; | |
| return function(C, P) { | |
| F.prototype = P.prototype; | |
| C.prototype = new F(); | |
| C.uber = P.prototype; | |
| C.prototype.constructor = C; | |
| } | |
| } | |
| // 对象的浅复制 | |
| function extend(parent, child) { | |
| var i; | |
| child = child || {}; | |
| for (i in parent) { | |
| if (parent.hasOwnProperty(i)) { | |
| child[i] = parent[i] | |
| } | |
| } | |
| return child; | |
| } | |
| // 对象的深复制 | |
| function extendDeep(parent, child) { | |
| var i, | |
| toStr = Object.prototype.toString, | |
| astr = '[Object Array]'; | |
| child = child || {}; | |
| for (i in parent) { | |
| if (parent.hasOwnProperty(i)) { | |
| if (typeof parent[i] === "object") { | |
| child[i] = (toStr.call(parent[i]) === astr) ? [] : {}; | |
| extendDeep(parent[i], child[i]); | |
| } else { | |
| child[i] = parent[i]; | |
| } | |
| } | |
| } | |
| return child; | |
| // 绑定方法到特定的对象上 | |
| function bind(o, m) { | |
| return function() { | |
| return m.apply(o, [].slice.call(argument)); | |
| } | |
| } | |
| } | |
| // ES5 bind polyfill | |
| if (typeof Function.prototype.bind === 'undefined') { | |
| Function.prototype.bind = function (thisArg) { | |
| var fn = this, | |
| slice = Array.prototype.slice, | |
| args = slice.call(arguments, 1); | |
| return function() { | |
| return fn.apply(thisArg, args.concat(slice.call(arguments))); | |
| } | |
| } | |
| } | |
| // 单体模式思想在于保证一个特定类仅有一个实例 | |
| // 闭包实现单体 | |
| // 第一次调用时,返回this。第二次,第三次调用时,将执行重写构造函数。 | |
| function Universe() { | |
| var instance = this; | |
| this.start_time = 0; | |
| this.bang = "Big"; | |
| Universe = function() { | |
| return instance; | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment