我有以下的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