zoukankan      html  css  js  c++  java
  • 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)));    
            };    
        };
    }
  • 相关阅读:
    [转]Torch是什么?
    去掉 CONSOLE 窗口(转)
    最短路径问题
    最短路,dijstra算法
    最短路,floyd算法,图的最短路径
    freckles
    还是畅通工程,最小生成树kruskal
    More is better
    畅通工程
    人见人爱
  • 原文地址:https://www.cnblogs.com/fengyuqing/p/javascript_extend_other.html
Copyright © 2011-2022 走看看