2016-09-18 67 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