基本类
function Person(){
this.name = 'zhangsan'
this.age = 20
this.run = () => {
console.log( this.name + '在运动' )
}
}
let p = new Person()
console.log(p)
构造函数和原型链中增加方法
类的静态方法
function Person(){
this.name = 'zhangsan'
this.age = 20
this.run = () => {
console.log( this.name + '在运动' )
}
}
Person.prototype.work = function() {
console.log( this.name + '在工作' )
}
Person.getInfo = function(){
console.log('静态方法getInfo')
}
let p1 = new Person()
p1.run()
p1.work()
Person.getInfo()
继承
- 对象冒充继承
缺点: 无法继承原型链上的属性和方法
function Person(){
this.name = 'zhangsan'
this.age = 20
}
Person.prototype.work = function() {
console.log( this.name + '在工作' )
}
function Web(){
Person.call(this)
}
let w1 = new Web()
console.log(w1.name)
w1.work()
- 原型链继承
缺点: 实例化子类的时候没法给父类传参
function Person(name, age){
this.name = name
this.age = age
}
Person.prototype.work = function() {
console.log( this.name + '在工作' )
}
function Web(){
}
Web.prototype = new Person()
let p1 = new Person('zhangsan', 30)
console.log(p1.name)
p1.work()
let w1 = new Web()
console.log(w1.name)
w1.work()
- 对象冒充+原型链组合继承
function Person(name, age){
this.name = name
this.age = age
}
Person.prototype.work = function() {
console.log( this.name + '在工作' )
}
function Web(name, age){
Person.call(this, name, age)
}
Web.prototype = Person.prototype
let p1 = new Person('zhangsan', 30)
console.log(p1.name)
p1.work()
let w1 = new Web('lisi', 50)
console.log(w1.name)
w1.work()
console.log(p1, w1)