javascript多种继承方式(函数式,浅复制,深复制,函数绑定和借用)
函数式继承:
var object = function (obj) { if (typeof Object.create !== 'undefined') { return Object.create(obj); } else { var F = function () {}; F.prototype = obj; return new F(); } };
浅复制继承:
function extend(Parent, Child) { var Child = Child || {}, i; for (i in Parent) { Child[i] = Parent[i]; } return Child; }
深复制:
function deepCopy(Parent, Child) { var Child = Child || {}, toStr = Object.prototype.toString, astr = "[object Array]", i; for (i in Parent) { if (typeof Parent[i] === 'object') { Child[i] = toStr.apply(Parent[i]) === astr ? [] : {}; deepCopy(Parent[i], Child[i]); } else { Child[i] = Parent[i]; } } return Child; }
函数绑定和借用:
function method(o, m) { return function () { return m.apply(o, [].slice.call(arguments)); }; } 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))); }; }; }