Javascript对象创建的最佳实践

Ala*_*ock 5 javascript closures creation object

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

            });
Run Code Online (Sandbox Code Playgroud)
  1. 我的对象构建方法是一种好的做法吗?

  2. undefined试图访问时进入helperFunc this.prop3.

  3. 我也尝试分配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;
                    ...
    
    Run Code Online (Sandbox Code Playgroud)

...当在helperFunc中调用它时,如下所示:

                       return this.getTotal();
Run Code Online (Sandbox Code Playgroud)

..我得到this.getTotal的不是一个功能

我一直在阅读对象创建和使用闭包来模仿私人成员等等,因为没有一种方法来定义对象我感到困惑.

TBH - 我真的不明白这个结构:

                       var myObject = (function() { ... } ();
Run Code Online (Sandbox Code Playgroud)

我已经看到它在jQuery插件中使用了很多但是第一个parenth在结尾处跟着空的parenth是什么意思呢?

任何知识都会受到高度赞赏.

另外,我已经订购了关于javascript的道格拉斯克罗克福德书,直到它到来我需要尝试解决这个问题

ofi*_*ofi 4

引用Xhalent的精彩文章提到的精彩文章(写得非常好,写得很清楚):

\n\n
\n

这是因为\xe2\x80\x9cthis\xe2\x80\x9d 的值与创建对象时\xe2\x80\x9cthis\xe2\x80\x9d 的值不同。

\n
\n\n

所以在你的情况下:

\n\n
...\n  var _this = this.prop3;\n  function helperFunc() {\n    return _this;\n  }\n...\n
Run Code Online (Sandbox Code Playgroud)\n\n

可能会达到想要的效果。

\n