1.简介
面向对象的特性: 封装 复用 继承
其中继承是面向对象最显著特性,继承是从已有的构造函数中派生出新的构造函数,新的构造函数可以吸收已有构造函数的属性和方法,又能扩展新的能力
2.继承的方式
(1)拷贝继承: 即浅拷贝(只拷贝对象的第一层属性,就是复制一个对象给另一个对象)
1 var father = { 2 name: 'wl', 3 age: 50, 4 houses: ['别墅', '大别墅'], 5 play: function() { 6 console.log('打球') 7 } 8 } 9 var son = { 10 name: 'wk, 11 } 12 function copy(o1,o2) { 13 for(var k in o1) { 14 if(o2[k]) { 15 continue; 16 } 17 o2[k] = o1[k] 18 } 19 } 20 copy(father, son); 21 console.dir(son)
执行结构如下所示:
深拷贝: 即拷贝对象的多层属性
本质是使用了递归
1 var s1 = { 2 name: 'wl', 3 age: 50, 4 houses: ['别墅', '大别墅'], 5 dog: { 6 name: '大黄', 7 age: 8 8 } 9 } 10 var s2 = {}; 11 12 function deepCopy(o1,o2) { 13 for(var k in o1) { 14 if(o1[k] instanceof Array) { 15 o2[k] = []; 16 deepCopy(o1[k], o2[k]) 17 } else if(o1[k] instanceof Object) { 18 o2[k] = {}; 19 deepCopy(o1[k], o2[k]) 20 } else { 21 o2[k] = o1[k] 22 } 23 } 24 } 25 26 deepCopy(s1, s2) 27 console.dir(s2)
执行结果如下所示:
(2)原型继承
1 function Person() { 2 this.name = '小明', 3 this.age = 20, 4 this.sex = '男' 5 } 6 7 function Student() { 8 this.score = 100 9 } 10 11 Student.prototype = new Person() // 在Student的原型对象上创建一个Person的实例 12 Student.prototype.constructor = Student // 修改原型对象之后,需要重新制定构造函数的指向 13 14 var s = new Student() 15 console.dir(s)
执行结果如下所示:
(3)构造函数继承
1 function Person(name, age, sex) { 2 this.name = name, 3 this.age = age, 4 this.sex = sex 5 } 6 Person.prototype.sayHi = function() { 7 console.log(this.name + '打招呼') 8 } 9 function Student(name, age, sex, score) { 10 Person.call(this, name, age, sex) 11 this.score = score 12 } 13 var s1 = new Student('小明',20,'男',100) 14 console.dir(s1)
执行结果如下所示:
(4)组合继承(原型继承+构造函数继承)
1 function Person(name, age, sex) { 2 this.name = name, 3 this.age = age, 4 this.sex = sex 5 } 6 Person.prototype.sayHi = function() { 7 return (this.name + '打招呼') 8 } 9 10 function Student(name, age, sex, score) { 11 Person.call(this, name, age, sex) 12 this.score = score 13 } 14 Student.prototype = new Person() 15 Student.prototype.constructor = Student 16 17 var s1 = new Student('小明',20,'男',100) 18 console.log(s1.sayHi())
执行结果如下所示:
(5)原型链继承
(6)寄生式继承
(7)寄生组合式继承