javascript - Javascript 如何将值从 "super class"传递到 "child class"

标签 javascript oop object inheritance constructor

我很清楚 javascript 不是基于类的语言。

话虽如此,这里是我们在 JavaScript 中进行继承的示例(方法之一):

function Person(name, age) {
        this.name = name;
        this.age = age;
    }

    Person.prototype.introduceSelf = function() {
        console.log("My name is " + this.name + " and I'm " + this.age);
    }

    function Employee(name, age, employeeID) {
        Person.call(this, name, age);
        this.employeeID = employeeID;
    }

    Employee.prototype = Object.create(Person.prototype);

    Employee.prototype.sayEmployeeID = function() {
        console.log('My Employee ID is: ' + this.employeeID);
    }

    var joe = new Employee('Joe', 22, 42);
    joe.introduceSelf() // returns: My name is joe and I'm 22
    joe.sayEmployeeID() // returns: My Employee ID is: 42

我的问题是:如何简单地调用 Person.call(this, name,age) 在 Employee 构造函数中,调用 new Employee(...)

时会生成具有 nameage 属性的对象

我知道它正在调用 Person 函数,thisEmployee 中的上下文,但尚不清楚属性如何到达结果对象。 “幕后”究竟发生了什么?

最佳答案

I understand that it's calling the Person function with the this being the context within Employee

您是否也了解“Employee 内的上下文”是什么?它是 new 实例,即结果对象,是 new 运算符在运行构造函数主体之前创建的(new Employee 中的 Employee)。请参阅What is the 'new' keyword in JavaScript?了解详情。

It's not clear how the properties get onto the resulting object. What exactly is happening "under the hood?"

属性由分配创建:

this.name = name;
this.age = age;
…
this.employeeID = employeeID;

同样,this 指的是结果对象。在前两种情况下,因为the call methodPerson 上显式使用,在后一种情况下,因为 newEmloyee 上使用。

关于javascript - Javascript 如何将值从 "super class"传递到 "child class",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46802132/

相关文章:

c++ - C++中类字段对齐与对象实例对齐的关系?

c# - 从 C# 方法返回不同类型

oop - MATLAB parfor 和 C++ 类 mex 包装器(需要复制构造函数?)

c++ - 选择类对象字段的构造函数

javascript - 如何向(对象的)嵌套 javascript 数组添加属性?

java - 设计: Use class or instance references?

javascript - 无法使用 JQuery/CSS 选择子元素 :nth-child selector

javascript - 请解释 .call(false) 的奇怪行为

JavaScript - 使用 RegExp 匹配字母数字模式

javascript - async.parallel 内的 async wait,回调变得未定义