Javascript中的继承 [英] Inheritance within Javascript

查看:294
本文介绍了Javascript中的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Javascript中的继承概念,我正在查看的教程使用此代码:

I'm studying the concept of inheritance in Javascript, and the tutorial I'm looking at uses this code:

// define the Student class
function Student() {
  // Call the parent constructor
  Person.call(this);
}

// inherit Person
Student.prototype = new Person();

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

我的问题是,为什么有必要同时调用父构造函数, Person.call(this),并将 Student 原型设置为等于新的 Person 对象(即 Student.prototype = new Person(); )?

My question is, why is it necessary to both call the parent constructor, Person.call(this), and set the Student prototype equal to a new Person object (i.e. Student.prototype = new Person();)?

推荐答案

有两个单独的问题要处理。

There are two separate issues to deal with.

首先是确保新的 Student 对象继承自 Person 对象。这就是你做 Student.prototype = new Person()的原因。这使 Student.prototype 一个所以学生对象将继承该对象继承的任何内容(来自 Person.prototype

The first is to make sure new Student objects inherit from Person objects. That's why you do Student.prototype = new Person(). That makes the Student.prototype a Person so Student objects will inherit whatever that object inherits (from Person.prototype).

第二个是将 Person 构造函数中的任何行为应用于任何新的 Student 对象。这就是你做 Person.call(this)的原因。如果 Person 构造函数没有任何修改新对象的代码,这在技术上是不需要的,但是如果你添加一些代码,它仍然是一个好主意。至以后。

The second is to apply any behavior in the Person constructor to any new Student objects. That's why you do Person.call(this). This is technically not needed if the Person constructor doesn't have any code that modifies the new object, but it's still a good idea to do it just in case you add some code to Person later.

附注,设置时继承,最好这样做:

Side note, when setting up the inheritance, it's better to do:

Student.prototype = Object.create(Person.prototype)

...和shim Object.create 如果需要的话。这样你实际上不需要调用 Person 构造函数来获取一个继承自 Person.prototype 。同样,有时候不是问题,但有时在构造函数中存在设置继承时不希望出现的副作用。

...and shim Object.create if needed. This way you don't actually need to invoke the Person constructor in order to get a new object that inherits from Person.prototype. Again, sometimes not an issue, but sometimes there are side effects in the constructor that are undesired when setting up the inheritance.

这篇关于Javascript中的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆