<script>
var Employee = new function(name)
{
this.name=name;
}
Employee.prototype.getName = function()
{
return this.name;
}
var PermanenetEmployee = new function(annualsalary)
{
this.annualsalary=annualsalary;
}
var employee = new Employee("rahul");
PermanenetEmployee.prototype = employee;
var pe = new PermanenetEmployee(5001);
document.write(pe.getName());
</script>
我在java脚本中实现继承。从这段代码我想打印员工名称,如“rahul”。但我得到的错误就像Uncaught TypeError:无法设置未定义的属性'getName'(匿名函数)。如何解决此错误?
Employee.prototype.getName = function()
{
return this.name;
}
答案 0 :(得分:2)
这是问题所在:
var Employee = new function(name)
// ------------^^^
{
this.name=name;
}
(PermanenetEmployee
也一样。)
你不希望new
在那里。 new
调用该函数。您希望稍后这样做,就像分配给employee
时一样。
请注意,您在它们之间设置继承的方式是反模式。要使PermanenetEmployee
正确“子类化”Employee
,请执行以下操作:
PermanenetEmployee.prototype = Object.create(Employee.prototype);
PermanenetEmployee.prototype.constructor = PermanenetEmployee;
不
var employee = new Employee("rahul");
PermanenetEmployee.prototype = employee;
...然后PermanenetEmployee
接受name
并将其传递给Employee
:
var PermanenetEmployee = function(name, annualsalary) {
Employee.all(this, name); // <====
// ...
};
...或更好地使用,使用ES2015(“ES6”)class
(如果你需要,例如使用Babel进行转换)。
这是一个正确的设置。我还在PermanenetEmployee
中修正了拼写错误:
var Employee = function(name) {
this.name = name;
};
Employee.prototype.getName = function() {
return this.name;
};
var PermanentEmployee = function(name, annualSalary) {
Employee.call(this, name);
this.annualSalary = annualSalary;
};
// Set up subclass
PermanentEmployee.prototype = Object.create(Employee.prototype);
PermanentEmployee.prototype.constructor = PermanentEmployee.prototype;
PermanentEmployee.prototype.getAnnualSalary = function() {
return this.annualSalary;
};
// Using
var pe = new PermanentEmployee("Rahul", 5001);
console.log(pe.getName());
console.log(pe.getAnnualSalary());
使用ES2015:
class Employee {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class PermanentEmployee extends Employee {
constructor(name, annualSalary) {
super(name);
this.annualSalary = annualSalary;
}
getAnnualSalary() {
return this.annualSalary;
}
}
// Using
var pe = new PermanentEmployee("Rahul", 5001);
console.log(pe.getName());
console.log(pe.getAnnualSalary());
同样,请注意,如果要在野外使用该语法(现在),则需要进行转换。
答案 1 :(得分:0)
有几种方法可以让你继续在JS中工作,我正在使用这种模式。
首先声明基础原型:
Employee = function () {
};
Employee.prototype = {
getName: function () {}
};
然后继承基础的原型:
PermanentEmployee = function () {
Employee.call(this);
};
PermanentEmployee.prototype = Object.create(Employee.prototype);
PermanentEmployee.constructor = PermanentEmployee;
PermanentEmployee.prototype.foo = function() {}