![](/img/trans.png)
[英]Javascript module is variable in function not accessing the outer scope variable
[英]javascript accessing a member function from outer scope variable
我一直在 jsfiddle 中嘗試一些 js 代碼,似乎我無法讓下面的所有這些代碼組合工作..
//combination #1
function get_set() {
this.get = function () {
document.write("get");
};
this.set = function () {
document.write("set");
};
};
var x = get_set; // storing function reference in x
x.get(); //invoking doesnt work.
//combination#2
var get_set = function() {
this.get = function () {
document.write("get");
};
this.set = function () {
document.write("set");
};
};
get_set.get(); //doesnt work as well..
有什么我想念的嗎? 提前感謝您的建設性建議/指出任何錯誤。 將不勝感激任何幫助。
您要么必須創建一個新的get_set
實例
var x = new get_set();
或者在get_set
你必須使用return this;
讓這個例子工作。
您的get_set
function 是構造函數function。 它旨在創建(“構造”)自身的實例。 為了完成這項工作,您需要關鍵字new
。 所以
var getset = new get_set;
創建 get_set 的實例。 現在可以使用getset.set
和getset.get
方法。
在這種情況下,也許您可以使用 Object 文字創建一個唯一實例:
var get_set = {
get: function () {
document.write("get");
},
set: function () {
document.write("set");
}
};
現在您不需要new
關鍵字並且方法可以立即使用( get_set.get
, get_set.set
)
使用 x=new get_set; 那可行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.