javascript
【Infragistics教程】在javascript构造函数中创建基本继承
2019獨角獸企業重金招聘Python工程師標準>>>
【下載Infragistics Ultimate最新版本】
用javascript創建對象有四種方法。具體如下:
繼承的實現因對象創建方法而異。本文將解釋如何在函數構造函數之間創建繼承。
假設您有一個函數:
| 1 2 3 4 | function animal(name, age) { ????this.name = name; ????this.age = age; } |
如果使用new操作符調用animal函數,將創建一個對象。這種對象創建方式也稱為“構造函數調用模式”。
| 1 2 3 4 | var dog =?new animal('foo', 5); console.log(dog); var cat =?new animal('koo', 3); console.log(cat); |
對象dog和cat都有自己的名稱和年齡屬性。如果希望在所有對象之間共享屬性或方法,請將其添加到函數原型中。
| 1 2 3 4 | animal.prototype.canRun =?function () { ?? ????console.log('yes ' +?this.name +?' can run !'); } |
使用javascript原型鏈,dog和cat對象都可以訪問canrun方法。
| 1 2 3 4 5 | var dog =?new animal('foo', 5); dog.canRun();?// yes foo can run ? var cat =?new animal('koo', 3); cat.canRun();?// yes koo can run |
接下來,讓我們創建另一個構造函數——人:
| 1 2 3 4 5 6 7 8 | function human(name, age, money) { ????this.name = name ; ????this.age = age ; ????this.money = money; } human.prototype.canEarn =?function () { ????console.log('yes ' +?this.name +?'can earn'); } |
此時,人與動物的功能沒有任何關系。然而,我們知道人也是動物。人工構造有兩個問題。
上述兩個問題可以通過在動物和人類功能構建者之間創建繼承來消除。
您可以通過如下修改人工函數來解決代碼復制的問題1:
| 1 2 3 4 | function human(name, age, money) { ????animal.call(this, name, age); ????this.money = money; } |
現在,在人類函數中,我們使用call方法手動傳遞當前對象作為動物函數中“this”的值。這種方法也稱為間接調用模式。現在,可以創建一個人類對象實例,如下所示:
| 1 2 | var h1 =?new human('dj', 30,?'2000 $'); console.log(h1); |
到目前為止,我們已經解決了代碼復制的第一個問題,但是人類的功能仍然與動物的功能無關。如果您嘗試對h1對象調用canrun方法,javascript將向您拋出一個錯誤。
| 1 | h1.canRun();?// throw error canRun is not a function |
您可以通過將人類功能原型與動物功能構造函數原型鏈接來解決這個問題。有兩種方法可以做到這一點。
使用γ原型
使用object.create()方法
您可以使用object.create()鏈接函數構造函數的原型,如下所示:
| 1 | human.prototype = Object.create(animal.prototype); |
您可以使用_uu proto_uuu鏈接函數構造函數的原型,如下所示:
| 1 | human.prototype.__proto__ = animal.prototype; |
更推薦object.create()方法,因為在許多瀏覽器中可能不支持_uuProto。在鏈接原型之后,在一種方式下,您已經在動物和人類函數構造函數之間創建了繼承。人的對象實例可以讀取動物功能的所有屬性,并且可以執行動物功能方法。
下面列出了實現函數構造函數之間繼承的完整源代碼,供您參考:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | function animal(name, age) { ?? ????this.name = name; ????this.age = age; ?? } ?? animal.prototype.canRun =?function () { ?? ????console.log('yes ' +?this.name +?' can run !'); } ?? var dog =?new animal('foo', 5); dog.canRun(); ?? var cat =?new animal('koo', 3); cat.canRun(); function human(name, age, money) { ????animal.call(this, name, age); ????this.money = money; } ?? human.prototype = Object.create(animal.prototype); ?? human.prototype.canEarn =?function () { ????console.log('yes ' +?this.name +?'can earn'); } // human.prototype.__proto__ = animal.prototype; var h1 =?new human('dj', 30,?'2000 $'); h1.canRun(); h1.canEarn(); |
要在函數構造函數之間創建繼承,請始終執行以下兩個操作:
轉載于:https://my.oschina.net/u/4009527/blog/2995846
總結
以上是生活随笔為你收集整理的【Infragistics教程】在javascript构造函数中创建基本继承的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 客户端SDK测试思路
- 下一篇: java并发编程——线程池的工作原理与源