簡體   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