我正在學習Javascript中的原型繼承,並且試圖編寫一個從子方法的原型調用父方法的示例。但是,我沒有得到我預期的結果。Javascript中的繼承 - 來自子方法的父方法調用
Person.js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greeting = function() {
console.log("Hello, My name is " + this.name + " and I am " + this.age + " years old.")
}
module.exports = Person;
Employee.js
var Person = require('./Person');
var Employee = function(name, age, salary) {
Person.call(this, name, age);
this.salary = salary;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.greeting = function() {
Person.prototype.greeting.call(this);
console.log("My salary is " + this.salary)
}
module.exports = Employee;
Test.js
var Person = require('./Person');
var Employee = require('./Employee');
var p = new Person("Rob", 24);
p.greeting();
var e = new Employee("Jim", 25, 1200000);
e.greeting();
所以基本上我是一個Person
類有name
和age
和greeting
方法附加到它的原型打印一些數據。 Employee
類擴展Person並且具有附加屬性salary
。它也通過打印工資來覆蓋greeting
方法。但是,在打印salary
之前,它會調用super class'
問候語方法,然後打印salary
。
我預期的產量爲:
Hello, My name is Rob and I am 24 years old.
Hello, My name is Jim and I am 25 years old.
My salary is 1200000
但實際產出:
Hello, My name is Rob and I am 24 years old.
Hello, My name is Person and I am 25 years old.
My salary is 1200000
我知道()調用方法需要與一起傳遞參數上下文this
。它的名稱是this (Person)
,它被替換爲名稱,它告訴我這些類不是純粹繼承的,因爲我在調用裏面的方法。我應該可以在裏面使用super.methodName()
,但超級在這裏不起作用。
請告訴我,我所做的是如何實現JS的繼承或如果我做錯了什麼。
PS:我試圖用一個超級呼叫問候像Java編寫,但它給了我一個錯誤。這是否意味着Employee類沒有擴展Person類?
重命名屬性'this.name'在'Person',它與'函數衝突。名稱的財產。 – Teemu