2015-05-07 26 views
0

需要將someObject.config.title的值更新爲從click事件中設置的值。我如何去做這件事?從專用內部函數更新變量值

也有一個單獨的問題,有什麼辦法可以設置$this作爲一個全局變量,可以通過此對象的任何子功能訪問?

jsFiddle

var someObject = { 
    config: { 
     title: '' 
    }, 
    init: function() { 
     // Any way to set $this as a global var that can accessed through any of the child functions of this object? 
     var $this = this, 
      title = $this.config.title; 

     $('button').on('click' , function() { 
      title = 'yo, waz gud son!'; 
      // This reference works 
      //$this.referenceTitle(title); 
     }); 
     // This reference is undefined, need to update original value 
     $this.referenceTitle(title); 
    }, 
    referenceTitle: function(arg) { 
     console.log(arg); 
    } 
} 

someObject.init(); 
+0

試過了,沒有工作。即使在點擊按鈕後 – Shivam

回答

2

在你的代碼someObject.config不是私人。

使之成爲私有變量(並獲得$this參考),你可以這樣做:

var someObject = (function() { 
    var config = { 
     title: '' 
    }; // config is now a private variable 

    var $this = { 
     init: function() { 
      var title = config.title; 

      $('button').on('click' , function() { 
       title = 'yo, waz gud son!'; 
       // This reference works 
       //$this.referenceTitle(title); 
      }); 
      // This reference is undefined, need to update original value 
      $this.referenceTitle(title); 
     }, 
     referenceTitle: function(arg) { 
      console.log(arg); 
     } 
    }; 
    return $this; 
}()); // <-- immediate invocation 

someObject.init();