これが問題である:(。そしてPermanenetEmployee
も同じ)
var Employee = new function(name)
// ------------^^^
{
this.name=name;
}
あなたはそこ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と一緒に蒸散)を使用してください。
ここで正しい設定です。あなたがいる場合transpileする必要があることに注意し、再び
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());
:
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を持つ:私はまたPermanenetEmployee
のタイプミスを修正しましたその構文を野生で使用したい(今のところ)。