JavaScript 继承:父类构造函数错误修复
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript 继承:父类构造函数错误修复</title>
</head>
<body>
<script>
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
<pre><code> sum() {
console.log(this.x + this.y)
}
}
class Son extends Father {
constructor(x, y) {
// this.x=x;
// this.y=y;
// 调用父类的构造方法,将参数x,y传给了父类的constructor
super(x, y)
}
}
var son = new Son(1, 2);
son.sum();
</script>
</body>
</code></pre>
</html>
<p>代码没有明显的语法错误,但是在 Father 类 的构造函数中,this.x 和 this.y 是没有被定义的。也就是说,构造函数应该接收 x 和 y 作为参数,并将它们赋值给 this.x 和 this.y。修改后的代码如下:</p>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript 继承:父类构造函数错误修复</title>
</head>
<body>
<script>
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
<pre><code> sum() {
console.log(this.x + this.y)
}
}
class Son extends Father {
constructor(x, y) {
// this.x=x;
// this.y=y;
// 调用父类的构造方法,将参数x,y传给了父类的constructor
super(x, y)
}
}
var son = new Son(1, 2);
son.sum();
</script>
</body>
</code></pre>
</html>
原文地址: https://www.cveoy.top/t/topic/ohNU 著作权归作者所有。请勿转载和采集!