Что происходит, когда мы используем «новый» оператор для создания экземпляра для объекта в javascript? И, во время создания, когда назначается прототип для конструктора? Я пытаюсь динамически назначить новый прототип в конструкторе, но результат довольно странно:Динамически назначать прототип в конструкторе не работает
function Person(name, age){//the super class constructor
this.name = name;
this.age = age;
if (typeof this.sayName != "function") {//set the function in prototype so Person's instance or subType can share just one instance of function(since function in javascript is Object indeed)
Person.prototype.sayName = function(){
console.log("my name is ", this.name);
}
}
}
//if I assign Student's prototype here, not in its constructor, it will be OK, but why not encapsulate it within the constructor if I can?
//Student.prototype = new Person();
function Student(name, age, school, grade){//the subType constructor
Person.call(this, name, age);//get the super class property
this.school = school;//init the subType property
this.grade = grade;
if (!(Student.prototype instanceof Person)) {//just assign the prototype to Student for one time
Student.prototype = new Person();
}
}
let person1 = new Student("Kate", 23, "Middle school", "3.8");
let person2 = new Student("Gavin", 23, "Middle school", "3.8");
let person3 = new Student("Lavin", 23, "Middle school", "3.8");
person1.sayName();//Uncaught TypeError: person1.sayName is not a function
person2.sayName();//my name is Gavin
person3.sayName();//my name is Lavin
- , так как «sayName()» может присвоить прототип человека, мы можем сделать вывод о том, что прототип будет готов, когда код конструктора
- основание в точке 1, в конструкторе Student(), почему я не могу заменить оригинальный прототип? (person1 не найдет функцию sayName)
- , когда назначен прототип для конструктора? И где я могу заменить прототип по умолчанию?
@smarber, спасибо за ваше объяснение и ссылку «http://stackoverflow.com/a/17393153/1507546». Но на самом деле я смутил, почему person1 не может получить метод sayName, а person2 и person3 могут? и мне любопытно, что происходит, когда мы новый объект. – blueGhost
Вы должны прокомментировать его сообщение, а не на свой пост, иначе он не получит уведомление. :) –