2016-08-18 32 views
-1

我有一個範圍界定問題。我有一個簡單的對象文字函數,有很多方法。我想打電話給調用對象文字函數與此返回TypeError

var myObjectFunc = function() { 

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

    }, 
    method3: function() { 

    }, 
    method4: function() { 

    } 
} 
} 

我試圖與 '本' 無數的方式方法4(),從方法1():

嘗試之一:

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 
+0

你的第二次嘗試似乎正在工作。 'myObjectFunc()。method1()'給出''Peter''。 –

+0

你是如何調用'method1()'的? – Thomas

回答

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; 
} 
+0

謝謝,這似乎工作。雖然這是像這樣寫文字的正確方法嗎?我試圖學習最佳實踐 –

+0

如果你想讓對象能夠訪問自己,這是 - afaik - 做到這一點。 'this'運算符只能在函數中使用,而不能在對象中使用。 –

+0

@ThorJacobsen事實並非如此。例如:'({a:function(){console.log(this)}})。a()'返回對象。 –

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'