[英]Call parent class' constructor function via call()
// Parent class
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log("Hello. My name is " + this.name);
};
Person.prototype.sayGoodbye = function() {
console.log("Goodbye!");
};
// Child class
function Student(name, gpa) {
Person.call(this, name);// I'm confused what does keyword 'this' refer to?
this.gpa = gpa;
}
// create child object
let john = new Student("john",3.5);
关键字“this”指的是 object john 还是 Person.prototype?
Student("john",3.5);
之前的new
运算符; 创建一个新实例 object,原型为以下函数的prototype
属性,然后使用新创建的 object 作为其this
值调用 function。 (有关更多详细信息,请参阅 MDN 上的new operator
文档。)
所以this
在
Person.call(this, name);
是学生 object 在存储到john
变量之前由new
创建并返回。
然后, Student
代码使用自己的this
值调用Person
function,以便Person
构造函数可以在从Student
返回之前将“Person”类型的属性添加到Student
object。
值得注意:
该示例显示了在 JavaScript 中执行class
关键字之前如何构建 class 对象
这个特定的例子没有通过Student
对象实现 inheritance 的Person.prototype
属性。 这是有时使用虚拟Person
object 作为Student
的原型来实现的,使用的代码类似于:
Student.prototype = new Person(); Student.prototype.constructor = Student;
这种做法的缺点和局限至少促成了class
构造函数在 ECMAScript 中的引入。
这里要让 Student 成为孩子 class,你需要将它扩展到 Person class:
class Person {
var name;
constructor(name) {
this.name = name;
}
sayhello(){
console.log("Hello. My name is " + this.name);
}
sayGoodbye(){
console.log("Goodbye!");
}
}
class Student extends Person {
getName(){
return this.name;
}
}
student = new Student("Jhon");
'this' 关键字指的是当前的 object。您可以使用子 class object 本身从子 class 调用父 class 的方法,因为您正在使用扩展关键字。
这是 inheritance 的一个简单示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.