3

Studentから継承するPerson次の例を考えてみましょう。

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ますか?

必要な場合の例を教えてください。

4

1 に答える 1

1

この SO の質問プロトタイプの継承を読んでください。obj->C->B->A ですが、obj.constructor は A です。なぜですか? .

それはあなたの答えを与えるはずです。


于 2011-11-17T14:27:30.247 に答える