即对象为非构造函数,普通函数继承另一个普通函数。
object()方法
浅拷贝
深拷贝(推荐)
object()方法
json发明人Douglas Crockford,提出的object()函数。
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
该函数就是把子对象的prototype属性,指向父对象。使用时依然是先继承后定义子对象的方法和属性
var parent = {
name: "Oliver"
};
var child = object(parent); //先继承
child.age = 18; //后定义
console.log(child.name); //Oliver
console.log(child.age); //18
浅拷贝
function extend(p) {
var c = {};
for(var i in p){
c[i] = p[i];
}
c.uber = p;
return c;
}
该方法只能继承基本数据类型,如果父对象有数组等对象,拷贝的只是个地址,子对象属性的改变会导致父对象属性的改变(篡改问题)
var parent = {
name: "Oliver",
friend: [1,2,3]
};
var child = extend(parent); //先继承
child.age = 18;
console.log(child.name); //Oliver
console.log(child.age); //18
child.friend.pop();
console.log(child.friend); //两者都改变了
console.log(parent.friend); //两者都改变了
深拷贝
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 parent = {
name: "Oliver",
friend: [1, 2, 3]
};
var child = deepCopy(parent); //先继承
child.age = 18;
console.log(child.name); //Oliver
console.log(child.age); //18
child.friend.pop();
console.log(child.friend); //[1, 2]
console.log(parent.friend); //[1, 2, 3]