美文网首页
[前端]JS-非构造函数的继承

[前端]JS-非构造函数的继承

作者: 喵吉呀呀 | 来源:发表于2018-12-06 22:28 被阅读0次

    1、object()方法

    示例

    var Chinese = {
      nation:'中国'
    };
    var Doctor ={
        career:'医生'
    }
    function object(o) {
        function F() {}
        F.prototype = o;
        return new F();
      }
    Doctor = object(Chinese);
    Doctor.career = '医生';
    console.log('Doctor:',Doctor); // Doctor: F {career: "医生"}
    console.log('Doctor.nation:',Doctor.nation); // Doctor.nation: 中国
    

    2、浅拷贝(这也能叫继承?[冷静一下])

    var Chinese = {  
        nation: '中国'
    };
    var Doctor = {    
        career: '医生'
    } 
    function extendCopy(p) {    
        var c = {};    
        for (var i in p) {      
            c[i] = p[i];    
        }    
        c.uber = p;    
        return c;  
    }
    Doctor = extendCopy(Chinese);
    Doctor.career = '医生';
    console.log('Doctor:', Doctor); // Doctor: F {career: "医生"}
    console.log('Doctor.nation:', Doctor.nation); // Doctor.nation: 中国
    
    • 缺点:因为是浅拷贝,相当于只是个指针的引用,子对象的属性修改后会影响父对象的属性
      如下
    var Chinese = {  
        nation: '中国',
        birthPlaces: ['北京', '上海', '香港']
    };
    var Doctor = {    
        career: '医生'
    } 
    function extendCopy(p) {    
        var c = {};    
        for (var i in p) {      
            c[i] = p[i];    
        }    
        c.uber = p;    
        return c;  
    }
    
    var Doctor = extendCopy(Chinese); 
    Doctor.career = '医生';
    
    Doctor.birthPlaces.push('厦门');  
    
    console.log('Doctor.birthPlaces:', Doctor.birthPlaces); // ["北京", "上海", "香港", "厦门"]
    console.log('Chinese.birthPlaces:',Chinese.birthPlaces); // ["北京", "上海", "香港", "厦门"]
    

    3、深拷贝

    var Chinese = {  
        nation: '中国',
        birthPlaces: ['北京', '上海', '香港']
    };
    var Doctor = {    
        career: '医生'
    }
    
    // 递归复制
    function deepCopy(p, c) {    
        var c = c || {};    
        for (var i in p) {      
            if (typeof p[i] === 'object') {        
                c[i] = (p[i].constructor === Array) ? [] : {};        
                deepCopy(p[i], c[i]);      
            } else {         
                c[i] = p[i];      
            }    
        }    
        return c;  
    }
    var Doctor = deepCopy(Chinese); 
    Doctor.career = '医生';
    
    Doctor.birthPlaces.push('厦门');  
    
    console.log('Doctor.birthPlaces:', Doctor.birthPlaces); // ["北京", "上海", "香港", "厦门"]
    console.log('Chinese.birthPlaces:', Chinese.birthPlaces); // ["北京", "上海", "香港"]
    

    仅作为学习笔记,有误请指正,玻璃心不接受批评
    参考:http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance_continued.html

    相关文章

      网友评论

          本文标题:[前端]JS-非构造函数的继承

          本文链接:https://www.haomeiwen.com/subject/sdiacqtx.html