我接受了很多关于javascript的采访。始终很常见的一个问题是“如何实现继承,请举例说明”。
我向面试官解释的内容与MDN site
中的内容大致相同我的一段代码:
//Parent Class
var Employee = function(name,salary) {
this.name = name;
this.salary = salary;
}
Employee.prototype.WelcomeMessage = function() {
return ("Welcome "+this.name)
}
Employee.prototype.getSalary = function() {
return this.salary
}
//Child Class
var Infra = function(name,salary) {
Employee.call(this,name,salary);
//Child should have its own get Salary method
Infra.getSalary = function() {
return "this is salary for child"
}
}
Infra.prototype = Object.create(Employee.prototype);
Infra.prototype.constructor = Infra ;
// Created instance of child to achieve Inheritance
var childInstance = new Infra("Jack","$1000")
childInstance.name //Return Jack
childInstance.WelcomeMessage() //Return Welcome Jack
childInstance.getSalary //return "this is salary for child" - this method was
// overridden by child
但是,每次我举这个例子时,面试官都不同意这种解决方案。他们在此继承示例中说“ Infra.prototype.constructor = Infra;”使用,不建议这样做。您应该将Object.assign与自调用函数一起使用以实现继承。
我通常会说这也能达到预期的效果,对此进行辩护,而MDN也给出了相同的结果。
实现继承的正确方法是什么?