2013-02-01 59 views
4

我定義了一個RequireJS模塊(見下文)。它是網站上每個頁面所需的功能集合。'this'關鍵字可以在RequireJS模塊中使用嗎?

返回對象initTwitter()中的函數之一需要在同一對象中調用另一個函數shortenURL()。我得到一個控制檯錯誤,讀取,「TypeError:this.shortenURL不是一個函數。」

所有這些函數最初都是在一個正常的Javascript單例對象中,並且代碼運行良好。我是RequireJS的新手,所以我不確定這個關鍵字在RequireJS中的工作方式不同,或者我只是在做錯誤的事情。

編輯:我也嘗試刪除'這',但我得到一個「ReferenceError:shortenURL未定義」的消息,而不是。編輯2:事實證明,在我的代碼'這'是在另一個函數內,所以它的範圍改變爲窗口。在進入函數之前,我需要保留這個範圍。

initTwitter: function() { 
      var bitly_obj = '', 
       $bitly_link = '', 
       self = this; /* Preserve scope of this */ 

      var twitterShortenUrl = function(obj, $elem) { 
        self.shortenURL(obj.url, function(url) { 
         $elem.attr('href', 'http://twitter.com/home?status=' + 'From @Real_Simple ' + obj.headline + ' ' + url); 
        }); 
       }; 
/* rest of code .... */ 

否則,Paul的答案強調我可以返回任何東西並添加初始化。

+3

除非RequireJS做一些['bind'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function /綁定)調用(它可能),'this'值是在執行時基於[如何調用函數]確定的(http://stackoverflow.com/questions/12370851/understanding-javascript-scope-with -var-認爲,這種/ 12371105#12371105)。 – apsillers

+0

事實證明,由於'this'在另一個函數內,所以範圍確實變爲'window' – Stephen

+0

'this' is'window' because * how * you called'twitterShortenUrl':'twitterShortenUrl(...); '如果你把它叫做'someObj.twitterShortenUrl(...);',那麼'this'就是'someObj'。 – apsillers

回答

6

不,因爲Require.js不會爲this做任何魔術綁定。你應該重寫模塊是一個實例對象:

define(['config', 'jquery'], function(config, $) { 
    function obj() { 
     this.initNav(); 
     this.initTwitter(); 
     this.initFullSiteLink(); 
    } 
    obj.prototype = { 
     doesObjPropertyExist: function (/*...*/) { /*...*/ }, 
     shortenURL: function (/*...*/) { /*...*/ }, 
     initTwitter: function (/*...*/) { /*...*/ }, 
     initFullSiteLink: function (/*...*/) { /*...*/ }, 
     initNav: function (/*...*/) { /*...*/ }, 
     omniture: function (/*...*/) { /*...*/ } 
    }; 
    return obj; 
}); 

require(['that_main_module'], function (obj) { 
    var newObj = new obj(); 
}); 
+0

感謝您的建議。事實證明,這個調用是在另一個函數內,所以這個調用的範圍變成了「窗口」。但是你的信息很有用。我不知道我實際上可以從模塊中返回一個命名對象,因爲文檔使用了未命名的對象。謝謝。 – Stephen

相關問題