繁体   English   中英

通过 call() 调用父类的构造函数 function

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM