2016-09-18 78 views
-1

這裏是我的代碼 我有兩個類 1.帶有一個函數first()的分類賬。 2.供應商無功能。如何調用javascript子類中的父類函數

現在我想調用供應商類中的first()函數。

https://gyazo.com/bea7ef497b58d390e279d3e2ea668431

var ledger = function(){}; 
ledger.prototype = { 

    first : function(){ 
     alert('first function is being called!'); 
    } 
} // END OF ledger CLASS 

var supplier = function(){} 
supplier.prototype = { 

    first(); 

} // END OF supplier CLASS 

jQuery(function(){ 

    // INHERITANCE 
    supplier.prototype = create.Object(ledger.prototype); 

}); 

在此先感謝張貼要求的問題

+0

99%的有[MCVE] 請張貼的JavaScript/jQuery的,CSS和HTML這將是有關你的問題。使用任何或所有以下服務創建演示: [Plunker.co](http://plnkr.co/), [jsFiddle.net](https://jsfiddle.net/), [CodePen。 io](https://codepen.io/), [JS Bin](https://jsbin.com/) 或片段(位於文本編輯器工具欄或CTRL + M上的第7個圖標)。 – zer00ne

回答

2
var Ledger = function() {}; 

Ledger.prototype.first = function() { 
    console.log("First!"); 
}; 

var Supplier = function() { 
    Ledger.call(this); 
}; 

Supplier.prototype = Object.create(Ledger.prototype); 
Supplier.prototype.constructor = Supplier; 

Supplier.prototype.second = function() { 
    console.log("Second!"); 
    this.first(); 
}; 

var supplier = new Supplier(); 

// First! 
supplier.first(); 

// Second! 
// First! 
supplier.second(); 

console.log(supplier instanceof Ledger); // true 
console.log(supplier instanceof Supplier); // true 
+0

哇!問題已解決。 非常感謝。 – Vipin

+0

你可以看看下面的https://jsfiddle.net/d8put1cu/ – Vipin

+1

@Vipin是的。首先,你不能將一個對象分配給'prototype',否則你會覆蓋之前的內容。如果你還想這樣做,你可以使用'Object.assign()'來保留之前的內容。其次,你必須在Object.create()調用之後實現'second()'方法。我已經改變了你的代碼,現在它工作。看看:https://jsfiddle.net/LLczxj8L/ – felipeptcho

相關問題