在 ES6 出现 class 关键字出现之前,通常使用构造器来模拟类:
方法一: 直接在构造器中修改 this,给 this 添加属性。
function c1(){
this.p1 = 1;
this.p2 = function(){
console.log(this.p1);
}
}
var o1 = new c1;
o1.p2();
方法二: 修改构造器的 prototype 属性指向的对象。
function c2(){
}
c2.prototype.p1 = 1;
c2.prototype.p2 = function(){
console.log(this.p1);
}
var o2 = new c2;
o2.p2();
在 ES6 出现 class 关键字出现之后,类的构建更加便捷和明了。
使用 class 关键字创建类: 将数据型成员写在constructor里面,将方法通过括号和大括号的形式写在constructor外面。
以上两种方式可以用class写成下面形式:
class c3{
constructor(){
this.p1=1;
}
p2(){
console.log(this.p1)
}
}
let o3=new c3();
o3.p2();
另外, class 关键字构造类时,可以使用get/set 关键字来创建 getter,通过 extends 关键字继承父类。
例如:
class Animal {
constructor(name) {
this.name = name;
}
barks() {
console.log(this.name + ' barks.');
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
run() {
console.log(this.name + ' run.');
}
}
let d = new Dog('MyDog');
d.barks(); // MyDog barks.
d.run(); // MyDog run.