原型继承的3种实现
1 利用call实现冒充对象继承,继承了模板的属性和方法,未继承原型属性和方法
function Person(name, age) {
this.name = name
this.age = age
}
function Student1(name,age,sex) {
Person.apply(this, arguments)
this.sex = sex
}
var s1 = new Student1('lili', 1, 'man')
console.log(s1)
2 利用prototype实现继承,缺点无法向父类传参
function Person(name, age) {
this.name = name
this.age = age
}
function Student2(sex) {
this.sex = sex
}
Student2.prototype = new Person('xiaoming', 2)
Student2.prototype.constructor = Student2
var s2 = new Student2('women')
console.log(s2.name, s2.sex, s2.constructor)
3 混合继承
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.hello = function (){
console.log('world')
}
function Student3(name,age,sex) {
Person.call(this,...arguments)
this.sex = sex
}
Student3.prototype.__proto__ = Person.prototype
var s3 = new Student3('ming',3,'man')
console.log(s3.name,s3.sex,s3.hello,s3.constructor)