我有以下的javascript:Javascript對象創建最佳實踐
var MyObject = (function() {
function Setup(args) {
this.prop1 = args.x;
this.prop2 = args.y
this.prop3 = this.prop1 + this.prop2;
this.Create = function() {
return 'a' + helperFunc();
}
function helperFunc() {
return this.prop3;
}
}
return {
init : function(args) {
var setup = new Setup(args);
setup.Create();
}
}
})();
$(function() {
MyObject.init(someArgs);
});
是我的做法提出異議建設一個好的做法呢?
嘗試訪問
this.prop3
時,我在幫助功能中獲得undefined
。我也試圖分配
this.prop1 + this.prop2
到一個局部變量,用函數返回此值,像這樣:function Setup(args) { var total; this.prop1 = args.x; this.prop2 = args.y total = this.prop1 + this.prop2; this.getTotal = function() { return total; }; this.prop3 = this.prop1 + this.prop2; ...
...並在helperFunc這樣調用這個時候:
return this.getTotal();
..我得到this.getTotal
是不是一個函數
我一直在閱讀周圍的對象創建和使用閉包來模仿私人成員等,因爲沒有一種方法來定義對象,我感到困惑。
TBH - 我真的不明白的結構:
var myObject = (function() { ... }();
我已經看到它使用了很多在jQuery插件但隨後空parenth什麼第一parenth在到底是什麼意思,做?
任何知識的傳授將不勝感激。
另外,我有秩序的道格拉斯Crockford的書JavaScript和直到它到達我需要嘗試解決這個問題
http://stackoverflow.com/questions/3921922/what-does-this-mean-function-x-y-a-b-in-javascript – mplungjan 2011-05-17 12:25:16
這裏有很多問題。如果你試圖限制自己每個問題的一個問題,它會使得提供準確和精確的答案變得容易很多。 – 2011-05-17 12:32:04
mplungjan - 這是理解函數調用結束時的父類的完美鏈接。我只需要了解爲什麼調用函數時調用屬性而不是函數時會出現undefined ... – 2011-05-17 12:40:51