javascript - 如何在 'modules' 中组织我的代码?

标签 javascript object scope closures this

我正在努力组织我的代码。我的项目中有几个模块,我想对其进行组织。

关键是我想到的一切都行不通。我目前正在考虑四个想法:

  1. 简单对象 - 由于范围问题没有用。使用 this.a 可以,但是 this 根据调用者的不同而具有不同的含义,因此它不可靠。例如,我曾经将一个函数分配给 WebSocket 类,但在调用该函数时突然 this 引用了 WebSocket 实例通过 WebSocket 事件。我可以在每次调用该函数时使用 bind(foo),但我猜一定还有另一种方法。

    var foo = {
        a: 3,
        s: function() {
            alert(a); // a doesn't exist in this scope
            alert(this.a); // 'this' isn't always foo
            alert(foo.a); // I would have to put 'foo.' before each variable
                          // reference, but I'm sure that's not the way to do it
       }
    };
    
  2. 实例 - a 未定义。再次强调,这个并不可靠。

    var foo = function() {
        this.a = 3;
        this.s = function() {
            alert(a);
        };
    };
    var foo_instance = new foo();
    foo_instance.a = 4;
    foo_instance.s(); // Error: a is not defined
    
  3. 实例关闭 - 不返回任何内容;它保持未定义

    var foo = (function() {
        this.a = 3;
        this.s = function() {
            alert(a);
        };
    })();
    // foo === undefined
    
  4. 使用 getter/setter 闭包 - 在 Chrome 上运行良好,但 IE 不支持 getter/setter。

    var foo = (function() {
        var a = 3;
        return {
            get a() { return a; },
            set a(v) { a = v; },
    
            s: function() {
                alert(a); // Doesn't work in IE as getters/setters are
                          // not supported
            }
        };
    })();
    

如何有效地组织我的模块,以便我可以安全地以跨浏览器的方式访问属性?

谢谢。

最佳答案

3 未定义,因为您没有返回任何内容。不要将属性和方法分配给“this”,而是尝试这样做:

var foo = (function() {
    var self = {};

    self.someProperty = someValue;

    self.someFunction = function () {

    }

    return self;
}());

foo 现在将返回一个具有定义的属性和方法的对象。通过这种方式,您永远不必想知道“this”实际上指的是什么。

关于javascript - 如何在 'modules' 中组织我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5290989/

相关文章:

javascript - 如何从 Facebook 分享按钮获得响应?

javascript - 包含对象数组的过滤对象

swift - 通过 Swift 映射将 Realm 对象映射到 Dict

javascript - 如何从 API 获取结果并将其存储为全局变量?

javascript - MooTools/JavaScript 变量范围

variables - ColdFusion 非作用域与变量作用域 : performance vs. 可读性?

javascript - 使用 .each() 两次

javascript - 单击按钮时触发 ctrl+r、ctrl+a、ctrl+q 事件

Javascript Object.defineProperty 设置属性更改时触发的方法

php - 类 stdClass 的对象无法转换为字符串 PHP 问题