继承
什么是继承 ?
构造函数的属性继承:借用构造函数
function Person (name, age) {
this.type = 'human'
this.name = name
this.age = age
}
function Student (name, age) {
Person.call(this, name, age)
}
var s1 = new Student('张三', 18)
console.log(s1.type, s1.name, s1.age)
构造函数的原型方法继承:拷贝继承(for-in)
function Person (name, age) {
this.type = 'human'
this.name = name
this.age = age
}
Person.prototype.sayName = function () {
console.log('hello ' + this.name)
}
function Student (name, age) {
Person.call(this, name, age)
}
for(var key in Person.prototype) {
Student.prototype[key] = Person.prototype[key]
}
var s1 = new Student('张三', 18)
s1.sayName()
另一种继承方式:原型继承
function Person (name, age) {
this.type = 'human'
this.name = name
this.age = age
}
Person.prototype.sayName = function () {
console.log('hello ' + this.name)
}
function Student (name, age) {
Person.call(this, name, age)
}
Student.prototype = new Person()
var s1 = new Student('张三', 18)
console.log(s1.type)
s1.sayName()