js中的类和constructor
问题
一直搞不清constructor和super是干什么用的。
前提
了解js的继承
原型继承
原型继承是通过利用js的原型链
function People(name, age) {
this.name = name;
this.age = age;
}
People.prototype.sayName = function() {
console.log('my name is ' + this.name);
}
function Man() {}
Man.prototype = new People('小明', 20);
let m = new Man();
m.sayName();
call或者apply实现继承
利用call和apply可以绑定this
function People(name, age) {
this.name = name;
this.age = age;
}
People.prototype.sayName = function() {
console.log('my name is ' + this.name);
}
function Man() {
People.call(this, 20);
}
let m = new Man();
m.sayName();
js的类
其实js的类就是语法糖
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
}
class中的构造函数其实就相当于以前的这种写法
function Polygon(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
this.sayName = sayName;
}
function sayName() {
console.log('Hi, I am a ', this.name + '.');
}
只是不一样的写法,super是调用父类构造函数,参数就是传到父类构造函数的参数
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
}
class Square extends Polygon {
constructor(length) {
this.height;
// ReferenceError,super 需要先被调用!
/*
这里,它调用父类的构造函数的 length,
作为Polygon 的 width和 height.
*/
super(length, length);
/*
注意: 在派生的类中, 在你可以使用'this'之前, 必须先调用super()。
忽略这, 这将导致引用错误。
*/
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}