扫码关注官方订阅号
用js实现一个类P 包含成员变量a,成员变量b成员函数sum sum输出a与b的和,a,b默认值都为0.实现一个类M,M继承自P,在P的基础上增加成员变量c成员变量函数sum变成a,b,c的和
ringa_lee
class P{ constructor() { this.a = 0; this.b = 0; this.sum = function(){ console.log(this.a+this.b); return this.a+this.b } } } class M extends P{ constructor(a, b) { super(a, b ); // 调用父类的constructor(a,b) this.c = 0; this.sum = function(){ console.log(this.a+this.b+this.c); return this.a+this.b+this.c } } } var p = new P() console.log(p) p.sum(); var m = new M() console.log(m) m.sum()
function P(a,b){ this.a = a || 0; this.b = b || 0; } P.prototype.sum = function() { return this.a + this.b;} function M(a,b,c){ P.call(this,a,b); this.c = c || 0; } M.prototype = new P(); M.prototype.constructor = M; M.prototype.sum = function() { return this.a + this.b + this.c;} p = new P(1,2); m = new M(1,2,3); p.sum();// 3 m.sum(); //6
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
ringa_lee