【发布时间】:2016-10-25 10:49:42
【问题描述】:
我参考了this 问题/答案来了解原型继承。
我知道要扩展一个方法,我们需要在基类中定义Person.prototype.getName。这样在子类中就可以称为myCustomer.sayMyName();
答案中的代码可以总结如下:
function Customer(name) {
this.firstName = name;
};
function User() {
}
Customer.prototype.hi = function() {
console.log('Test method of parent');
}
User.prototype = new Customer('shaadi');
var myUser = new User();
myUser.hi();
但问题是如果我可以用以下语法调用相同的,我为什么要使用原型?
我的代码:
function Customer(name) {
this.firstName = name;
this.hi= function() {
console.log('Test method of parent');
}
};
function User() {
}
User.prototype = new Customer('shaadi');
var myUser = new User();
myUser.hi();
我可以在不定义Customer.prototype.hi的情况下使用parent的方法,那么为什么/何时应该使用Customer.prototype.hi?
如果两种解决方案都可以让我访问父母的方法,我为什么要选择前者?
【问题讨论】:
标签: javascript object inheritance prototype prototypal-inheritance