定义类
class Newclass {
constructor(name, age) {
this.name = name;
this.age = age
}
sayName () {
console.log('我是公共方法--定义在原型上', this.name)
}
}
let class1 = new Newclass('class1', '1')//我是公共方法--定义在原型上 class1
let class2 = new Newclass('class2', '2')//我是公共方法--定义在原型上 class2
console.log(class1.sayName() === class2.sayName());//true
console.log(class1.name === class2.name);//fales
ES6 的class
可以看作只是一个语法糖,constructor()构造方法如果不声明,会隐式提供一个空constructor,this指向的是实例;this显示绑定的属性为私有属性,而sayName()方法没有this显示绑定,则定义在原型上是公共方法。
如何继承
关键字extends
class Foo { constructor() { console.log(1); } } class Bar extends Foo { constructor() { super(); console.log(2); } } const bar = new Bar();
继承在前,实例在后
class Point { constructor(x, y) { this.x = x; this.y = y; } } class ColorPoint extends Point { constructor(x, y, color) { this.color = color; // ReferenceError super(x, y); this.color = color; // 正确 } }