ES5中的静态方法
function Person(name, age){
this.name = name
this.age = age
this.run = function () {
console.log(`${this.name}---${this.age}`)
}
}
Person.work = function () {
console.log('work')
}
var p = new Person('Carlo', 20) //实例方法是通过实例化来调用的
p.run()
Person.work() //静态方法是通过类名直接调用
ES5中的继承方式
function Person(name, age){
this.name = name
this.age = age
this.run = function () {
console.log(`${this.name}---${this.age}`)
}
}
Person.prototype.work = function () {
console.log('work')
}
function Web(name, age) {
Person.call(this, name, age)
}
var p = new Web('Lily', 18)
p.run() //Lily---18
p.work() //TypeError: p.work is not a function
- 原型链继承:可以继承构造函数里面以及原型链上面的属性和方法,实例化子类的时候没法给父类传参
function Person(name, age){
this.name = name
this.age = age
this.run = function () {
console.log(`${this.name}---${this.age}`)
}
}
Person.prototype.work = function () {
console.log('work')
}
function Web(name, age) {
}
Web.prototype = new Person()
var p = new Web('Lily', 18)
p.run() //undefined---undefined
p.work() //work
结合使用
function Person(name, age){
this.name = name
this.age = age
this.run = function () {
console.log(`${this.name}---${this.age}`)
}
}
Person.prototype.work = function () {
console.log('work')
}
function Web(name, age) {
Person.call(this, name, age)
}
Web.prototype = new Person()
var p = new Web('Lily', 18)
p.run() //Lily---18
p.work() //work
ES6中的静态方法
class Person {
constructor (name, age) {
this._name = name
this._age = age
}
getInfo () {
console.log(`${this.name}---${this.age}`)
}
static run () {
console.log('这是一个静态方法')
}
}
Person.neural = '这也是一个静态方法'
let p = new Person()
Person.run() //这是一个静态方法
console.log(Person.neural) //这也是一个静态方法
ES6中的继承方式
class Person {
constructor (name, age) {
this._name = name
this._age = age
}
getInfo () {
console.log(`${this.name}---${this.age}`)
}
run () {
console.log('run')
}
}
class Web extends Person {
constructor (name, age, gender) {
super(name, age)
this._gender = gender
}
getGender () {
console.log(this._gender)
}
}
let w = new Web('Lily', 18, 'girl')
w.getGender() //girl