这种用对象组织的代码 公用变量的定义是否一定要放在对象里?~

define(function () {
    var main = {
        temp: 'abc', // 在此定义
    
        init: function () {
            method();
            method0();
        },
        method: function () {
            console.log(this.temp);
        },
        method0: function () {
            var _this = this;
            
            console.log(this.temp);
            
            function test() {
                _this.temp = '123';
            }
        }
    };
});
define(function () {
    var temp: 'abc'; // 在此定义
    
    var main = {
        init: function () {
            method();
            method0();
        },
        method: function () {
            console.log(temp);
        },
        method0: function () {
            console.log(temp);
            
            function test() {
                temp = '123';
            }
        }
    };
});

第一种有特别烦人的 this 但是所有东西都没有越出对象 如果后续迭代页面逻辑升级比方说 同一个页实现 add modify 且逻辑相似 那是否就可以直接面向对象 继承 多态啥的了 ~
如果以对象来组织代码(并非故意面向对象 仅仅是页面逻辑代码 对象写法看起来清晰) 的话 有必要遵从吗

第二种敲好用的…… 欲罢不能~

阅读 2k
1 个回答

代码风格由你自己决定的,你觉得哪样好写就那样写就行了,不过需要注意的是万一要给别人看你源码的时候要让别人能看得懂就行,其实都差不多的。
当然第二种在一定程度上还可以私有化变量

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题