ES5中怎么声明一个类?
let Animal = function (type) {
this.type = type
}
Animal.prototype.eat = function () {
console.log('I am eating food')
}
let dog = new Animal('dog')
let monkey = new Animal('monkey')
dog.eat()
monkey.eat()
ES6中的类
函数声明和类声明之间的一个重要区别是函数声明会提升,类声明不会。
构造函数:constructor方法用于创建和初始化一个由class创建的对象。一个类只能拥有一个名为constructor的特殊方法。一个构造函数可以使用super关键字来调用一个父类的构造函数。
class Animal {
constructor(type) {
this.type = type
}
eat() {
console.log('i am eating food');
}
}
let dog = new Animal('dog')
let monkey = new Animal('monkey')
console.log(dog);
console.log(monkey);
dog.eat();
console.log(typeof Animal); // function
class的方式是function方式的语法糖
Setter&Getter(如何读取属性?)
let _age = 4;
class Animal {
constructor(type) {
this.type = type
}
get age() {
return _age
}
set age(val) {
if(val<7&&val>4){
_age = val
}
}
eat() {
console.log('i am eating food');
}
}
let dog = new Animal('dog')
console.log(dog.age);
dog.age = 8;
console.log(dog.age);
Static Methods(如何操作方法?)
静态方法是面向对象最常用的功能,在ES5中利用function实现的类是这么实现一个静态方法的。
let Animal = function(type) {
this.type = type
this.walk = function() {
}
}
Animal.eat = function(food) { // 静态方法
}
在ES6中使用static标记是不是静态方法
class Animal {
constructor(type) {
this.type = type
}
eat() {
Animal.walk();
console.log('i am eating food');
}
static walk() {
console.log('i am walking');
}
}
let dog = new Animal('dog')
dog.eat();
调用静态方法不需要实例化该类,但不能通过一个类实例调用静态方法。静态方法通常用于为一个应用程序创建工具函数。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
console.log(Point.distance(p1, p2));
如何继承一个类
面向对象之所以可以应对复杂的项目实现,很大程度要归功于继承。
在es5中怎么实现继承
// 定义父类
let Animal = function(type) {
this.type = type
}
// 定义方法
Animal.prototype.eat = function(food) { // 静态方法
console.log('i am eating');
}
// 定义子类
let Dog = function() {
// 初始化父类
Animal.call(this,'dog')
this.run = function() {
console.log('i can run');
}
}
// 继承
Dog.prototype = Animal.prototype
es6是怎么解决这些问题的?
- 使用extends创建子类:extends关键字在类声明或类表达式中用于创建一个类作为另一个类的子类
- 如果子类中存在构造函数,则需要在使用this之前先调用super()
class Animal {
constructor(type) {
this.type = type
}
walk() {
console.log('i am walking');
}
static eat() {
console.log('i am eatinh');
}
}
class Dog extends Animal {
constructor() {
super('dog')
}
run() {
console.log(' i can run');
}
}