2017-02-03 60 views
1

我有以下代碼(簡化)這個關鍵字和功能範圍在javascript

var Page = new UI('page.html'); 

Page.onLoad = function(html){ 

    this.name = 'Page 1'; 
    Util.test(this.run); 

}; 

Page.run = function(){ 

    console.log(this.name); // undefined 
    console.log(Page.name); // correct 

}; 

var Util = function(){}; 

Util.prototype.test = function(callback){ 

    // when finished run the callback 
    callback(); 

}; 

我的問題是,爲什麼當執行離開的對象,然後回來我不能使用this關鍵字?請解釋我應該改變什麼才能再次訪問this

+0

也許你的'.run'首先被執行,並且只會比'.onLoad'設置'this.name'?也可能你的UI頁面不會綁定'this'來運行,而且它總是功能本身? – Justinas

+0

@Justinas如果是這樣的話'Page.name'也是不確定的,我想 – slash197

回答

0

文章的頂部引用了另一篇關於'this'的文章,所以我認爲我只是提供了代碼。如果您閱讀其他帖子和鏈接的文章,您應該能夠遵循此代碼。

function UI(html) { 
    this.name = html; 
} 

UI.prototype = { 

    onLoad: function() { 
     util.test(this); 
    }, 

    run: function() { 
     console.log(this.name); 
    } 
} 

var util = (function() { 
    return { 
     test: function (ui) { 
      if (ui && ui.run) { 
       ui.run(); 
      } 
     } 
    } 
})(); 

var page = new UI("index.html"); 
+0

看看如何調用'Page.run':'callback();'... – Teemu