簡體   English   中英

如何在javascript中設置嵌套函數的變量

[英]how to set variable from nested function in javascript

我正在使用knockoutjs,這里是簡化的viewmodel:

  var app = function(){
     var self = this;
     this.index = 0;
     myfunction = function(){
         //how can i modify index here      
         self.index = 1;
     };
     console.log(self.index);  // i want to output 1 here , rather than 0
}; 

new app();​

謝謝 !

這是否與knockout.js特別相關,或者您只是試圖對一個簡單的ECMAScript問題進行排序? 任何...

通常最好不要使用聲明將要執行的函數表達式,並且構造函數應該以一個有限的字母開頭,讓其他人知道它們是構造函數。

function App() {
    var self = this;

目前還不清楚為什么要這樣做。 保持對此的引用在構造函數中並不常見。

    this.index = 0;
    myfunction = function(){

這是你遇到麻煩的地方。 當第一次調用consructor時,上面將創建一個名為myfunction的全局變量。 那可能不是你想要做的。 函數聲明將保持在本地,非常明確。 但無論如何,該功能應該在App.prototype上。

  function myFunction() {

      //how can i modify index here
      self.index = 1;
  };

該函數將修改index屬性,但僅在調用它時。 所以你可能會做的是:

function App(){
    this.index = 0;  // Each instance will have an index property
}

// All instances will share a myfunction method
App.prototype.myfunction = function() {
    this.index = 1;
    console.log(this.index);
}

var app = new App();
app.myfunction();  // 1

我會像這樣初始化函數:

this.myfunction = function(){ 
  self.index = 1;
};

然后打電話給它:

var test = new app();​

test.myfunction();
console.log(test.index);

初始化時不會調用您的函數,因此內部代碼不會被執行。

但是,在您的情況下,這應該足夠了(將您的代碼更改為與此類似):

myfunction();
console.log(self.index);  // i want to output 1 here , rather than 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM