我有以下的 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);
});
Is my approach to object construction a good practice?
I am getting
undefined
in the helperFunc when trying to accessthis.prop3
.I have also tried to assign
this.prop1 + this.prop2
to a local variable and use a function to return this value like so: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
不是一个函数。
我一直在研究对象创建和使用闭包来模拟私有成员等内容,由于没有一种定义对象的标准方式,我感到很困惑。
说实话,我真的不理解这个结构:
var myObject = (function() { ... } ();
我经常在jQuery插件中看到它被使用,但是第一个括号后面跟着空括号的意思和作用是什么呢?欢迎提供任何相关知识。
此外,我已经订购了Douglas Crockford的JavaScript书籍,在它到达之前,我需要尝试解决这个问题。