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

web3.js的Javascript设计模式原型错误,javascript,prototype,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

不知道我做错了什么,为我正在开发的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();

您可以使用Object.assign

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

当您想要创建一个或多个函数实例时,应该使用prototype

initweb3.prototype.testing = function(){ /* code goes here */}
.
.
. 
persona.testing();
在您的例子中,initweb3是一个构造函数。 确保构造函数以大写字母开头

例如:

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

  const p = new Person();
  p.sayHi();
在您的用例中,persona已经是一个实例对象,如果您想向它添加一个新函数,只需执行persona.testing=function{}

您还可以尝试扩展initweb3函数

initweb3.prototype.testing = function(){ /* code goes here */}
.
.
. 
persona.testing();
观看此视频以了解有关JavaScript原型的更多信息


好啊但我想知道我在代码中可能做错了什么。我也尝试过persona.prototype.testing,它让我无法设置未定义的属性。我还删除了原型中的其他方法,这样代码就不会太大,虽然该方法也不是这样工作的;对于单个函数可能还可以,但对于多个函数,我将使用Object.assign Object.assign接受3个参数:1个模板-在我们的案例中为空对象文本2个目标对象,我们扩展了3个新对象,该对象附加了n个MethodsHanks用于回复。如果我有更多的功能,并希望包括所有使用我上面使用的速记,我如何做,因为我尝试了上面的功能,但无法识别该功能。为了清晰起见,编辑了我的代码以包含更多的函数。@CharlesOkaformbah用initweb3.prototype替换persona.prototype,您应该很好。@CharlesOkaformbah您的示例中缺少一个逗号。initweb3.prototype={testing:function{console.log'Yes,我知道';},testing1:function{console.log'No,我不知道';};很酷,如果您对解决方案满意,请竖起大拇指。