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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)