关于Javascript继承,我可以'我不明白

There is something about Javascript inheritance that I can't understand

本文关键字:明白 Javascript 继承 我可以 关于      更新时间:2023-09-26

我正在阅读Mozilla开发者网络的面向对象JavaScript简介,在开始使用node.js之前,是时候学习如此严肃的JavaScript了。

无论如何,继承的事情对我来说似乎很模糊。从文档中复制和粘贴:

// define the Person Class
function Person() {}
Person.prototype.walk = function(){
  alert ('I am walking!');
};
Person.prototype.sayHello = function(){
  alert ('hello');
};

这很容易,但Student继承会使事情变得复杂。其他人认为以下三种说法本质上是一样的吗?

// 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;

我理解第一个(调用父构造函数),因为它与Java、PHP等非常相似。

为什么需要调用Student.prototypeStudent.prototype.constructor

需要一个明确的解释。为什么这个代码:

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

继承还不够用吗?

EDIT:关于构造函数的事情,这里已经回答了。

这不起作用:

function Student() {
  Person.call(this);
}
var student1 = new Student();

因为CCD_ 4的原型属性在CCD_ 5实例上不可用。Person.call(this)仅调用具有特定this值的Person(即Student实例)。但是Person函数是完全空的,所以在这里它什么都不做。CCD_ 11和CCD_ 12之间除了无用的CCD_。

为了得到Person的函数,.prototype赋值是必要的。

之前:

<a Student instance>
  its prototype: Student.prototype, with all student functions
    its prototype: Object.prototype

之后:

<a Student instance>
  its prototype: <a Person instance>, with all student functions if you add them
    its prototype: Person.prototype, with all person functions
      its prototype: Object.prototype

如果您使用Node.js,我建议您研究ECMAScript 5的对象创建方法。MDN在这里有一个页面,这可能是一个很好的指南。另请参阅John Resig对新方法的概述。当你使用Java这样的经典OO语言时,很难理解原型继承。祝你好运