繁体   English   中英

javascript原型继承混乱

[英]javascript prototypical inheritance confusion

下面是一个工作示例,以显示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。

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

将属性包装到函数返回中可以抽象实现。

例如,如果老板希望您提供this.amountDue的修饰结果,则只需更改getAmountDue方法的实现getAmountDue

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM