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)));    
            };    
        };
    }
  • 相关阅读:
    DOM
    JavaScript 数组的方法总结
    vuex 状态持久化插件 —— vuex-persistedstate
    移动端1px细线
    CSS多行文本并显示省略号
    Java面试题
    Git提交分支
    Redis的安装配置
    Spring IoC
    单例模式
  • 原文地址:https://www.cnblogs.com/wangking/p/10869420.html
Copyright © 2011-2022 走看看