gpt4 book ai didi

javascript - 我无法理解有关 Javascript 继承的一些内容

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:04:39 25 4
gpt4 key购买 nike

我正在阅读 Introduction to Object-Oriented JavaScript来自 Mozilla 开发者网络,在开始使用 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.prototype Student.prototype.constructor

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

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

var student1 = new Student();

继承还不够吗?

编辑:关于构造函数的事情,已经回答了here .

最佳答案

这行不通:

function Student() {
Person.call(this);
}

var student1 = new Student();

因为 Person 的原型(prototype)属性在 Student 实例上不可用。 Person.call(this) 仅使用特定的 this 值(即 Student 实例)调用 Person。但是 Person 函数完全是空的——所以在这里它什么也没做。 StudentPerson 之间没有任何关系,除了无用的 Person 调用。

要获得 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

关于javascript - 我无法理解有关 Javascript 继承的一些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12217648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com