es5中的类 构造函数
function Person(){
this.name = 'alex' // 属性
this.age = 22 // 属性
}
var p = new Person()
p.name // alex
构造函数和原型链增加方法
function Person(){
this.name = 'alex' // 属性
this.age = 22 // 属性
// 实例方法 new Person()调用
this.run = function () {
console.log(`${this.name}在运动`)
}
}
原型链上面的属性会被多个实例共享 构造函数不会
Person.prototype.sex = '男'
Person.prototype.work = function () {
console.log(`${this.name}在工作`)
}
静态方法
Person.getInfo = function () {
console.log('我是静态方法')
}
var p = new Person()
p.run()
p.work()
调用静态方法,直接类名调用,不用实例化
Person.getInfo()
es5的继承
function Person(){
this.name = 'alex'
this.age = 19
this.run = function () {
console.log(`${this.name}在运动`)
}
}
Person.sex = '男'
Person.prototype.work = function (){
console.log(`${this.name}在工作`)
}
Web类继承Person类 原型链+对象冒充的组合继承模式
function Web(){
// 对象冒充实现继承
Person.call(this)
}
var w = new Web()
w.run() // 对象冒充可以继承构造函数的属性和方法
w.work() // 报错 对象冒充可以继承构造函数的属性和方法 但是没法继承原型链上的属性和方法
原型链继承
function Teacher(){}
Teacher.prototype = new Person() // 原型链实现继承
// 原型链继承既能继承构造函数的属性和方法,也能继承原型链上的属性和方法
var t = new Teacher()
t.run()
t.work()
原型链实现继承问题
function Person(name, age){
this.name = name
this.age = age
this.run = function () {
console.log(`${name}在运动`)
}
}
Person.prototype.work = function () {
console.log(`${this.name}在工作`)
}
function Web(name, age){}
Web.prototype = new Person('lucy', 22)
var w = new Web('alex', 19) // 实例化子类的时候无法给父类传参
w.run() // lucy在运动
w.work() // lucy在工作
原型链+对象冒充的组合继承
function Person(name, age){
this.name = name
this.age = age
this.run = function () {
console.log(`${this.name}在运动`)
}
}
Person.prototype.work = function () {
console.log(`${this.name}在努力工作,因为他要还房贷`)
}
function Web(name, age) {
Person.call(this, name, age) // 冒充对象实例化子类可以给父类传参
}
Web.prototype = new Person('lucy', 19)
var w = new Web('alex', 28)
w.run() // alex在运动
w.work() // alex在努力工作,因为他要还房贷
原型链+对象冒充的另一种方式
function Person(name, age){
this.name = name
this.age = age
this.run = function () {
console.log(`${this.name}在运动`)
}
}
Person.sex = '男'
Person.prototype.work = function (){
console.log(`${this.name}在工作`)
}
function Web(name, age){
Person.call(this, name, age)
}
Web.prototype = Person.prototype
var w = new Web('lily', 19)