javascript:多種繼承方式(函數式,淺複製,深複製,函數綁定和借用)

 

函數式繼承:app

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;
}

深複製:post

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;
}

函數綁定和借用:this

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)));    
        };    
    };
}
相關文章
相關標籤/搜索