這里講了一個最最最簡單的JS中基於原型鏈的繼承和多態。
先看一下以下這段代碼的實現(A是“父類”,B是“子類”):
var A = function(){ this.value = 'a'; this.showValue = function(){ console.log(this.value); } } var a = new A(); a.showValue(); var B = function(){ this.value = 'b'; }; B.prototype = new A(); var b = new B(); b.showValue();
輸出結果為:
"a" "b"
- 1
- 2
- 1
- 2
結果看來實現了一個函數,不同對象的執行,出現不同的結果。
B.prototype = new A(); 這句將A“類”的構造方法,賦值給了B的構造原型,使B能夠繼承於A。
b.showValue()過程中,先在b中尋找showValue,無果。在b的原型:B,中尋找showValue,而B的prototype已經被A的構造方法賦值,因此再向上一層,在A中找到showValue。因此執行。
