我很清楚JavaScript不是基于类的语言。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)
员工构造函数,导致对象在致电时具有name
和age
属性new Employee(...)
据我所知,它调用Person函数,this
是Employee
中的上下文,但不清楚属性如何进入结果对象。到底发生了什么?“引擎盖下?”
我建议投入大量时间学习JavaScript关闭。 https://开头计算器。com/questions/111102/how-do-javascript-closures-work – Kris
@Kris与闭包无关,它只是javascript的本质,它在“dynamic”这个指针上运行,它驱动那些不理解它的人疯。这就是为什么你可以在javascript中“借用”函数,常用的模式是'Array.prototype.slice.call(nodeList)'在添加'Array.from'之前将'NodeList'转换为数组。' – Dummy
这是因为当'new'instanceof'Employee'被调用'Person'被称为宽度时,'this'被绑定到Employee的instanceof。 – PHPglue