原型继承 ://现代无类继承模式
- 基本代码:
var parent = { name : "Papa" } var child = object(parent); function object(o) { function F() {}; F.prototype = o; return new F(); }
选择继承的时候可以考虑,传入实例还是构造函数原型;
var child = object(parent); var child = object(Parent.prototype);
-
ECMA5中的实现: Object.create();
var child = Object.create(parent, { age: {value :2} });
通过复制属性实现继承
- 浅复制:
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 mix() { var arg, prop, child = {}; for(arg = 0; arg < arguments.length; arg += 1) { for(prop in arguments[arg]) { if(arguments[arg].hasOwnProperty(prop)) { child[prop] = arguments[arg][prop]; } } } return child; } var cake = mix( {eggs: 2, large: true}, {butter: 1, salted: true}, {flour: '3 cups'}, {sugar: 'sure!'} );
借用方法:重用一些方法,但不想形成继承关系;
- 利用apply/call;
- 利用bind;