即对象为非组织函数,一般函数继续另一个一般函数。
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]