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
call () 메서드는 context와 함께 인수를 전달해야 한다는 것을 알고 있습니다 this
. 그리고 this (Person)
내부에서 메서드를 호출하기 때문에 클래스가 순수하게 상속되지 않는다는 것을 나타내는 이름으로 대체되는 이름입니다. 나는 super.methodName()
내부 에서 사용할 수 있어야 하지만 슈퍼는 여기서 작동하지 않습니다.
내가 한 것이 JS의 상속이 어떻게 이루어 졌는지 또는 내가 잘못하고 있는지 알려주십시오.
추신 : 나는 자바에서와 같이 인사에 대한 슈퍼 호출을 사용하려고했지만 오류가 발생했습니다. Employee 클래스가 Person 클래스를 확장하지 않았 음을 의미합니까?
Employee.prototype = Object.create(Person)
기능에 할당 Employee.prototype
됩니다 Person
. 함수에는 name
속성 이 있으므로 특정 함수의 이름을 기록했습니다 : Person
.
Employee
예는 특성도 찾아보실 수 있습니다 3 개의 수영장이있다 :
첫 번째는 3 개의 속성이있는 Employee 인스턴스입니다.
두 번째는 1 개의 메소드가있는 Employee 프로토 타입 (prop가 Employee 인스턴스에 없으면 js가 여기에 표시됨)입니다.
세 번째는 하나의 메소드가있는 Person 프로토 타입 (prop가 이전 객체에서 발견되지 않은 경우 js가 여기를 참조)입니다.
greeting
가 on Employee.prototype
과 이므로 Employee 인스턴스에서 Person.prototype
액세스 할 수 없습니다. Person.prototype.greeting
항상 Employee.prototype.greeting
체인에서 더 가까운 곳에 의해 차단됩니다 . 그 이유는 다음과 같습니다.
Employee.prototype.greeting = function() {
Person.prototype.greeting.call(this);
console.log("My salary is " + this.salary)
}
Person.prototype.greeting
직접 호출해야합니다 ( this
함수 내부에는 Employee의 인스턴스가 있음)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다