javascript原型继承混淆

时间:2015-07-03 04:33:32

标签: javascript

下面是一个展示Javascript原型如何工作的工作示例。所以从我的理解是简单的客户实例继承了Person的原型功能。

var Person = function (name) {
    this.name = name;
};
Person.prototype.getName = function () {
    return this.name;
};
var john = new Person("John");
alert(john.getName());
Person.prototype.sayMyName = function () {
    alert('Hello, my name is ' + this.getName());
};
john.sayMyName();
var Customer = function (name) {
    this.name = name;
};
Customer.prototype = new Person();

var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
Customer.prototype.setAmountDue = function (amountDue) {
    this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function () {
    return this.amountDue;
};
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());

但有一点让我感到困惑的是作者为什么要做一个getAmountdue原型函数?它只是返回this.amountDue。

1 个答案:

答案 0 :(得分:0)

我认为这个问题与javascript原型继承无关。

要将属性包装到函数中,return可以抽象实现。

例如,如果您的老板希望您提供this.amountDue的装饰结果,则可以更改getAmountDue方法的实施。