var obj1 = {
name: 'zs',
age: 18,
sex: '男',
dog: {
name: '金毛',
age: 2
},
friends: ['ls', 'ww']
}
// 深拷贝 把o1的成员拷贝给o2
function deepCopy(o1, o2) {
for (var key in o1) {
// 获取key属性对应的值
var item = o1[key];
// 如果item 是对象?
// var o = {}
if (item instanceof Object) {
// var o = {};
o2[key] = {};
deepCopy(item, o2[key]);
} else if (item instanceof Array) {
// 如果item 是数组呢?
// var arr = [];
o2[key] = [];
deepCopy(item, o2[key]);
} else {
// 如果是简单类型
o2[key] = o1[key];
}
}
}
var obj2 = {};
deepCopy(obj1, obj2);
// 修改obj1中的成员 不会影响obj2
obj1.dog.name = 'xxx';
obj1.friends[0] = 'xxx';
console.dir(obj2);
JS对象继承
原型继承
// 1 原型继承
function Super() {
this.color = 'red';
}
function Sub() {
}
Sub.prototype = new Super();
Sub.prototype.constructor = Super;
var sub = new Sub();
console.log(sub.color);
原型继承的问题:无法给构造函数传参
借构造函数继承
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, score) {
Person.call(this, name, age, sex);
this.score = score;
}
var stu = new Student('zs', 18, '男', 100);
console.log(stu);
借用构造函数继承问题:无法重用方法
原型继承
// 结合原型继承和组合式继承
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
Person.prototype.sayHi = function () {
console.log(this.name);
}
function Student(name, age, sex, score) {
Person.call(this, name, age, sex);
this.score = score;
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
var stu = new Student('zs', 18, '男', 100);
console.log(stu);