И снова наследование
Господа, доброго времени суток.
Вопрос новичка, прошу помощи Почему так работает
function Parent(){
}
Parent.prototype = {
sayParent(){
console.log('im parent');
}
}
function Child(){
}
Child.prototype = Object.create(Parent.prototype);
//вопрос в механизме назначения методов
Child.prototype.sayChild = function(){
console.log('im child');
}
var test = new Child();
test.sayParent() // im parent
test.sayChild() // im child
А так нет
function Parent(){
}
Parent.prototype = {
sayParent(){
console.log('im parent');
}
}
function Child(){
}
Child.prototype = Object.create(Parent.prototype);
//вопрос в механизме назначения методов
Child.prototype = {
sayChild(){
console.log('im child');
}
}
var test = new Child();
test.sayParent() // im parent
test.sayChild() // НЕ РАБОТАЕТ
И как корректно определять большое количество методов для Child |
В строке 12 наследуете прототип, в строке 15 все удаляете и определяете прототип заново.
Отформатировать код можно тут: http://jsbeautifier.org/ |
Наследование обычно делается так (обратите внимание на свойство __proto__):
function Parent() {}
Parent.prototype = {
sayParent() {
console.log("im parent");
}
};
function Child() {}
Child.prototype = {
__proto__: Parent.prototype,
sayChild() {
console.log("im child");
},
myMethod() {},
myOtherMethod() {},
};
var test = new Child();
test.sayParent();
test.sayChild();
Тоже самое может быть записано так... (что является более предпочитаемой записью в JavaScript)
class Parent {
sayParent() {
console.log("im parent");
}
}
class Child extends Parent {
sayChild() {
console.log("im child");
}
myMethod() {}
myOtherMethod() {}
}
var test = new Child();
test.sayParent();
test.sayChild();
Цитата:
|
Большое спасибо.
|
| Часовой пояс GMT +3, время: 06:08. |