3

继承方式一:混入继承

"use strict";

//object:A
let Oa= {
    money: 'many money',
    resource: 'company,house',
    control: function (){
        console.log('this is function');
    }
};

//object:B
let Ob = {};
for (let k in Oa) {
    Ob['k'] = Oa['k'];
}

console.log(Ob.money);//'many money'
console.log(Ob.control()); //'this is function'

继承方式二:原型继承

//object:A
var Oa= {
    loveColor: 'Green',
    habbit: 'backetball',
    sayHi: function (){
        console.log('hello world');
    }
}

//创建构造函数,并且将对象A的地址赋值给构造函数的原型
function Func() {}
//实现继承
Func.prototype = Oa;
//恢复三角关系
Func.prototype.contructor = Func;

//实例化的所有对象都拥有对象Oa的属性和方法

//object:B
let Ob = new Func();

console.log(Ob.lovaColor); //'Green';
console.log(Ob.habbit); //'backetball';

继承方式三:混入加原型

//object:A
let Oa = {
    color: 'red',
    love: function (){
        console.log('love green');
    }
}

function Func(name){
    this.name = name;
}

for (let k in Oa) {
    Func.prototype[k] = Oa[k];
}

//object:B
let Ob = new Func('jeky');

console.log(Ob.color) // red;
Ob.love() // 'love green';

继承方式四:object.create();

//object:A
let Oa = {
    fName: 'apple',
    color: 'red'
};

//object:B
//实现过程:new了一个新的对象,把传入作为参数的那个对象设置给新创建的这个对象的原型属性
let Ob = Object.create(Oa); 
console.log(Ob.fName); //'apple'

蒋哲
353 声望11 粉丝