Web3.js的Javascript设计模式原型错误

时间:2017-04-12 05:02:35

标签: javascript prototype

不知道我做错了什么,为我正在研究的web3js应用程序创建了一个javascript原型。当我尝试在原型中调用函数时,它没有看到函数。当我检查console.log时,抛出“persona.testing()不是函数。

Web3 = require('web3');

if(typeof web3 != "undefined")
    web3 = new Web3(web3.currentProvider);
     else {
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
     }

var initweb3 = function(address,abi) {
        this.address = address,
        this.abi = abi;
        this.contract;
        web3.eth.defaultAccount = web3.eth.accounts[0];
        this.contract = web3.eth.contract(this.abi);
        this.contract = this.contract.at(this.address);
 }

var paddress = "0x0",
    pabi = "",

    maddress = "",
    mabi = "";
    persona = new initweb3(paddress,pabi);
    //minion = new initweb3(maddress,mabi);

persona.prototype = {

testing: function(){
  console.log('Yes, I know');
},

testing1: function(){
  console.log('No, I don't');
}
};


persona.testing();

2 个答案:

答案 0 :(得分:0)

您可以使用Object.assign

persona = Object.assign({}, persona, {
  testing: function(){
    console.log('Yes, I know');
  }
});

persona.prototype.testing = function(){};

答案 1 :(得分:0)

如果要创建一个或多个函数实例,则应使用prototype

在你的情况下initweb3是一个构造函数。 确保你的构造函数以大写字母开头。

例如:

  function Person(){ /*...*/ }
  Person.prototype.sayHi = function() { };

  const p = new Person();
  p.sayHi();
您的用例persona中的

已经是实例object,如果您想为其添加新功能,只需执行persona.testing = function() {}

OR

您还可以尝试扩展initweb3功能。

initweb3.prototype.testing = function(){ /* code goes here */}
.
.
. 
persona.testing();

观看此视频,了解有关JavaScript原型的更多信息。

https://www.youtube.com/watch?v=riDVvXZ_Kb4