我很清楚 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(...)
name
和 age
属性的对象
我知道它正在调用 Person 函数,this
是 Employee
中的上下文,但尚不清楚属性如何到达结果对象。 “幕后”究竟发生了什么?
最佳答案
I understand that it's calling the
Person
function with thethis
being the context withinEmployee
您是否也了解“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
method在 Person
上显式使用,在后一种情况下,因为 new
在 Emloyee
上使用。
关于javascript - Javascript 如何将值从 "super class"传递到 "child class",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46802132/