【问题标题】:java scrip object don't call function inside itjavascript对象不调用其中的函数
【发布时间】:2017-08-30 18:25:50
【问题描述】:

这段代码有什么问题?我想在类内的函数中将消息打印到 cnsole 中。

function Clas(x);
{
   this.x = x;
function nothing()
{
    console.log(x);
}
}
var clas = new Clas(1);
clas.nothing();

【问题讨论】:

    标签: function class logging console


    【解决方案1】:

    nothing() 未暴露。您需要将其附加到this

    function Something(x) {
      this.x = x;
      this.nothing = function() {
        console.log(this.x);
      }
    }
    
    var something = new Something(3);
    something.nothing(); // 3
    

    【讨论】:

      【解决方案2】:

      想要这样的东西吗? 您可以返回包含函数的 JSON 对象。 (所以它有点像 OOP。)

      function Clas(x) {
          return {
              x : x,
              nothing : function () {
                  console.log(x);
              }
          }
      }
      
      var clas = new Clas(1);
      clas.nothing();
      

      这里是小提琴:https://jsfiddle.net/juy2jdkp/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-17
        • 1970-01-01
        • 2015-11-16
        相关资源
        最近更新 更多