【问题标题】:can you use a constructor's method when defining a method in a seperate constructor在单独的构造函数中定义方法时可以使用构造函数方法吗
【发布时间】:2018-06-30 10:04:41
【问题描述】:

我可以这样做吗?如果不是为什么?有什么更好的解决方案?

function ConstructorA(){
  this.ten = function(){
    return 5+5;
  }
}

function ConstructorB(){
  this.fifteen = function(){
     var ten = ConstructorA.ten();
     return 5 + ten;
  }
}

【问题讨论】:

  • 你自己试过了吗?要调用ten,您需要通过ConstructorA 构造:var ten = new ConstructorA().ten()
  • 您可能正在寻找mix-ins
  • 您的描述含糊不清。它没有解释你最终想要做什么。我能说的最好的就是你想要一个类似static 的方法。如果是这样,那么将ten移到构造函数之外,直接放在函数上。 ConstructorA.ten = function() { return 5 + 5 }。如果您使用class 语法,则有一个static 关键字可以为此提供简写。

标签: javascript methods constructor


【解决方案1】:

您需要像这样使用 newConstructor() 调用构造函数:

function ConstructorA(){
  this.ten = function(){
    return 5+5;
  }
}

function ConstructorB(){
  this.fifteen = function(){
     var ten = new ConstructorA().ten();
     return 5 + ten;
  }
}

console.log(new ConstructorB().fifteen());

【讨论】:

    猜你喜欢
    • 2021-01-08
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2011-10-30
    • 2019-01-06
    • 1970-01-01
    • 2016-07-09
    相关资源
    最近更新 更多