[英]Access a javascript variable from a function inside a variable
您好,我有以下問題,我不太確定如何搜索:
function(){
var sites;
var controller = {
list: function(){
sites = "some value";
}
}
}
所以問題是如何從定義為
各種網站
編輯:
這是更完整的部分。 我正在使用marionette.js。 我不想定義附加到Module變量(下面的代碼)的變量,但將其私有給Module,希望這是有意義的。 這是有效的代碼:
Admin.module("Site", function(Module, App, Backbone, Marionette, $, _ ) {
Module.sites = null;
Module.Controller = {
list: function (id) {
Module.sites = App.request("site:entities");
}
};
});
我想代替
Module.sites = null;
去做
var網站;
這樣的事情確實有所作為吧? 因為在第一種情況下,我將從外部定義一個可訪問變量,而在第二種情況下,它將是私有變量。 我對javascript有點陌生,所以請嘗試使其變得簡單。
如果您正在尋找全局訪問權限,只需先在函數外部聲明變量,然后對函數內部的變量進行更改,然后就可以在需要時獲取該值。
免責聲明:我沒有使用木偶的經驗,但是,您所描述的聽起來很可行。
JavaScript最強大的功能(在我看來)是閉包。 這意味着從另一個函數中聲明的任何函數都可以訪問外部函數中聲明的變量。
例如:
var func;
function foo() {
var answer = 42;
func = function () {
// I have access to variable answer from in here.
return answer++;
};
}
// By calling foo(), I will assign the function func that has access "answer"
foo();
// Now I can call the func() function and it has access to the "answer"
// variable even though it was in a scope that doesn't exist anymore.
// Outputs:
// 42
// 43
console.log(func());
console.log(func());
這意味着,如果您按照描述的那樣在模塊定義函數中聲明了var站點,則應該可以從任何內部匿名函數中訪問它。 唯一的例外是Marionette重新編寫您的函數(通過使用Function函數和toString()),這似乎不太可能,但可能。
您的原始示例應該如上所述,我懷疑與您的范圍無關的代碼還有其他問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.