使用此返回的TypeError调用对象文字函数

时间:2016-08-18 10:38:03

标签: javascript this javascript-objects

我有一个范围问题。我有一个简单的对象文字函数,有许多方法。我试图从method1()

调用method4()
var myObjectFunc = function() {

return {
    method1: function() {
        // call method4 here and pass value
    },
    method2: function() {

    },
    method3: function() {

    },
    method4: function() {

    }
}
}

我用'this'尝试了很多方法:

尝试一个:

var myObjectFunc = function() {

var that = this;

return {
    method1: function() {
        // call method4 here and pass value
        var myName = 'Peter';
        that.method4(myName);
    },
    method2: function() {

    },
    method3: function() {

    },
    method4: function(val) {
        console.log(val);
    }
}
}

尝试二:

var myObjectFunc = function() {

return {
    method1: function() {
        // call method4 here and pass value
        var myName = 'Peter';
        this.method4(myName);
    },
    method2: function() {

    },
    method3: function() {

    },
    method4: function(val) {
        console.log(val);
    }
}
}

两者都返回错误:

TypeError: that.method4 is not a function

2 个答案:

答案 0 :(得分:0)

试试这个:

var myObjectFunc = function() {

  var ret = {
      method1: function() {
          // call method4 here and pass value
          var myName = 'Peter';
          ret.method4(myName);
      },
      method2: function() {

      },
      method3: function() {

      },
      method4: function(val) {
          console.log(val);
      }
  }

  return ret;
}

答案 1 :(得分:0)

试试这个:

const myObjectFunc = () => ({
  method1() {
    // call method4 here and pass value
    const myName = 'Peter'
    this.method4(myName)
  },
  method2() {

  },
  method3() {

  },
  method4(val) {
    console.log(val)
  }
})

然后:

myObjectFunc().method1()

记录'Peter'