0

我在我的代码中创建了一个 JS 对象(模块模式):

var Validator = {
    regexEmail: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/,

    settings: {
        error_class: "error-field",
        formValid: true
    },

    init: function (form, default_error_class) {
        self = this;
        alert(self == window);
    },
};

在 chrome 上运行“init”函数时,self == window(预期)为 false。但是当我在 IE9 上尝试它时,我得到了真实的(!)。你能告诉我为什么吗?我希望“this”能够捕获我的自定义 Validator 对象而不是窗口

4

4 回答 4

2

在定义“自我”时修正你的范围。此外,使用显式而非隐式比较器,即 === 而非 ==。

var Validator = {
    regexEmail: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/,

    settings: {
        error_class: "error-field",
        formValid: true
    },

    init: function (form, default_error_class) {
        var self = this;
        alert(self === window);
    },
};

Validator.init();
于 2013-03-24T09:25:40.820 回答
1

您可以使用立即执行的匿名构造函数

var Validator = new function(){
    this.regexEmail = 
        /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    this.settings = {
        error_class: "error-field",
        formValid: true
    };
    this.init = function (form, default_error_class) {
        console.log(this === window);
    };
    return this;
}();
Validator.init(); //=> false
于 2013-03-24T09:27:17.957 回答
0

我认为 IE 在这种情况下实际上是正确的。

var因为你在定义self它时没有使用隐式全局。当您尝试设置此全局self时,它会失败,因为浏览器中的全局对象window已经有一个window.self属性,它是对window.

HTML 生活标准 说

window、frames 和 self IDL 属性都必须返回 Window 对象的浏览上下文的 WindowProxy 对象。

这意味着它window.self应该是不可变的。

所以,window.self == window它提醒真实。

然而,由于历史黑客与一些旧网站保持兼容,WebKit 和 Gecko 中有一个错误/功能允许你覆盖它,即使你真的不应该这样做。似乎(至少在 Gecko 中)split objects有关。

于 2013-03-24T11:21:18.250 回答
0

使用 alert(self === window);而不是相等运算符。您也可以在此处查看接受的答案以获取有关 2 个运算符的更多详细信息:JavaScript 比较中应该使用哪个等于运算符 (== vs ===)?

还有一件事:正如天才所说,修复你的范围:

var self=this; 
于 2013-03-24T09:28:27.170 回答