原型链与继承
1 原型链继承
1:私有的name属性变公有(引用数据类型),(基本数据类型无影响)
2:无法传递参数
3:可以使用原型上的属性和方法
function SuperType (){
this.age = '18'
this.name = ['xh', 'zz']
}
SuperType.prototype.code = 'code'
SuperType.prototype.fun = function () {
console.log('方法')
}
function SubType () {
}
SubType.prototype = new SuperType()
var sys1 = new SubType()
sys1.age = '33'
sys1.name.push('??')
console.log(sys1.age) // 输出'33'
console.log(sys1.name)// 输出["xh", "zz", "??"]
console.log(sys1.fun) // 输出fun
console.log(sys1.code) // 输出code
var sys2 = new SubType()
console.log(sys2.age) // 输出'18'
console.log(sys2.name)// 输出["xh", "zz", "??"]
console.log(sys2.fun) // 输出fun
console.log(sys1.code) // 输出code
2 构造函数继承
1:解决了私有属性变公有的问题
2:可以传递参数
3:无法使用SuperType原型上的属性和方法
function SuperType (sex) {
this.age = '18'
this.name = ['xh', 'zz']
this.sex = sex
}
SuperType.prototype.code = 'code'
SuperType.prototype.fun = function () {
console.log('方法')
}
function SubType (val) {
SuperType.call(this, val)// 构造函数式继承
}
var sys1 = new SubType ('女')
sys1.age = '33'
sys1.name.push('??')
console.log(sys1.name)// 输出["xh", "zz", "??"]
console.log(sys1.age) // 输出'33'
console.log(sys1.sex) // 输出女
console.log(sys1.fun)// 输出undefined
console.log(sys1.code)// 输出undefined
var sys2 = new SubType ()
console.log(sys2.name)// 输出["xh", "zz"]
console.log(sys2.age) // 输出'18'
console.log(sys2.sex) // 输出undefined
console.log(sys2.fun)// 输出undefined
console.log(sys2.code)// 输出undefined
3:组合继承
结合原型链继承和构造i函数集成,取长补短。
用原型链继承实现对原型属性和方法的继承
用构造函数继承实现对实例属性的继承
构造函数继承在每一个实例中都创建了一个副本,更改其中的一个市里的属性不影响另外的实例
function SuperType (name) {
this.name = name
}
SuperType.prototype.code = 'code'
SuperType.prototype.fun = function () {
console.log('4 name:' + this.name)
return 'haha'
}
function SubType (name) {
SuperType.call(this, name) // 构造函数继承
}
SubType.prototype = new SuperType() // 原型链继承
SubType.prototype.constructor = SubType
var sys1 = new SubType('???')
sys1.code = 'nihao'
console.log(1, sys1.name)//输出???
console.log(2, sys1.code)//输出nihao
console.log(3, sys1.fun())//输出name:??? 输出haha
var sys2 = new SubType('++')
console.log(1, sys2.name)//输出++
console.log(2, sys2.code)//输出code
console.log(3, sys2.fun())//输出name:++ 输出haha
4:寄生式继承
function createAnother (val) {
var clone = Object.create(val)
clone.code = '110'
clone.sayHi = function () {
return this.name
}
return clone
}
var person = {
name: '??'
}
var animal = {
name: '牛'
}
var anotherP = createAnother(person)
var anotherA = createAnother(animal)
console.log(anotherP)
console.log(anotherP.sayHi())
console.log(anotherA)
console.log(anotherA.sayHi())
5:寄生组合式继承
function createAnother (child, father) { // 继承到一个干净的父类原型 var clone = Object.create(father.prototype) clone.constructor = child child.prototype = clone } function Father (name) { this.name = name; this.colors = ['red', 'blue'] } Father.prototype.sayname = function () { alert(1) } function Child (name) { Father.call(this, name) } createAnother(Child, Father) Child.prototype.sayAge = '15' var instance = new Child('小孩') console.log(instance)