我有以下 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);
});
我的对象构造方法是一个好习惯吗?
我
undefined
在尝试访问时进入了 helperFuncthis.prop3
。我也尝试分配
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 插件中使用了很多,但是最后的第一个括号后面是空括号是什么意思?
任何传授的知识将不胜感激。
另外,我已经订购了 Douglas Crockford 关于 javascript 的书,在它到达之前我需要尝试解决这个问题