学习内容:
- 类的定义
- 静态属性和方法的定义
- 类的继承
类的定义方法
其实ES中是没有类的概念的,但可以用function去模拟一个类。
属性定义在构造方法里,方法定义在原型里。
function Fruit(name) {
this.name = name
}
类中的方法不要直接写在function当中,应该写在类的原型下面:
function Fruit(name) {
this.name = name
}
Fruit.prototype.showname = function() {
...
}
静态方法和静态属性的定义方法
直接在类的后面写属性名和方法名就可以。
Fruit.price = 0
Fruit.getPrice = function() {
...
}
定义好之后,不需要new,直接调用即可。
类的继承
下面的例子可以看到,通过构造函数方法实现继承,只是继承父类的属性,父类的方法是无法继承的。
// 父类
function Animal(name) {
this.name = name
}
Animal.prototype.showname = function () {
console.log('name is : ' + this.name)
}
// 构造函数继承
// 子类
function Dog(name, age) {
Animal.call(this, name) // 继承属性
this.age = age
}
let dog1 = new Dog('yiyi','white')
console.log(dog1)
dog1.showname()
-------------------------------------------------------------------
Dog {name: 'yiyi', age: 'white'} // 继承属性可以
Uncaught TypeError: dog1.showname is not a function // 继承方法不可以
在上面程序的基础上增加原型继承,使用构造函数继承+原型继承的组合式继承实现继承父类的属性和方法:
// 父类
function Animal(name) {
this.name = name
}
Animal.prototype.showname = function () {
console.log('name is : ' + this.name)
}
// 构造函数集成
// 子类
function Dog(name, age) {
Animal.call(this, name) // 继承属性
this.age = age
}
Dog.prototype = new Animal()
Dog.prototype.constructor = Dog
let dog1 = new Dog('yiyi','1')
console.log(dog1)
dog1.showname()
// ---------------------------------------------------
// Dog {name: 'yiyi', age: '1'}
// 2-9.js?d238:7 name is : yiyi