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;
}
}
posted @   SultanST  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示