3
Student
Student
에서 상속하는 다음 예제를 고려하십시오.
Javascript에서 객체를 상속 할 때 "Subclass.prototype.constructor = Subclass"가 필요합니까?
function Person(name) {
this.name = name;
}
Person.prototype.say = function() {
console.log("I'm " + this.name);
};
function Student(name, id) {
Person.call(this, name);
this.id = id;
}
Student.prototype = new Person();
// Student.prototype.constructor = Student; // Is this line really needed?
Student.prototype.say = function() {
console.log(this.name + "'s id is " + this.id);
};
console.log(Student.prototype.constructor); // => Person(name)
var s = new Student("Misha", 32);
s.say(); // => Misha's id is 32
Student
오브젝트를 인스턴스화하고 해당 메소드를 호출하면 정상적으로 작동하지만 Student.prototype.constructor
은 Person(name)
를 리턴합니다.
Student.prototype.constructor = Student;
그러면 Student.prototype.constructor
가 예상대로 Student(name, id)
을 반환합니다.
항상 Student.prototype.constructor = Student
을 추가해야합니까?
필요시 예를 들려 줄 수 있습니까?
의 중복 가능성 [무엇 자바 스크립트 생성자 속성의 중요성?] (http://stackoverflow.com/questions/4012998/what-it-the-significance-of-the-javascript-constructor- 재산) – Domenic