现在有两个对象:

Man = {
    sex: 'male'
}
Student = {
    job: 'student'
}

我们希望student继承person,因为person和student都是普通的对象,不是构造函数,所以这里无法依赖于构造函数的继承。那方法是:
1: 创建一个以某个对象为蓝本而生成的对象

function object(parent){
    var F = function(){};
    F.prototype = parent;
    return new F();
}
var maleStudent = object(Man);
maleStudent.job = 'student';
maleStudent.sex === 'male';//true

2: 简单粗暴地拷贝所有的属性

function deepCopy(parent, child){
    var child = child || {};
    for (i in parent) {
        if(typeof parent[i] === 'object'){
            child[i] = parent[i].constructor === 'Array'? []: {};
            deepCopy(parent[i], child[i]);
        }
        else{
            child[i] = parent[i]
        }

    }
    return child;
}

var parent = {
    color: ['red', 'green'],
    name: {
        firstName: 'hehe',
        lastName: 'Ha'
    }

}
var child = deepCopy(parent);
child.color;// ['red', 'green']

nanaistaken
586 声望43 粉丝