0

这将是一个新手问题,但尽管答案可能很简单,但我很难理解这个概念。任何反馈将不胜感激

这是我的问题的简化版本

var x=(function(){
    this.load=function(){
        alert("this is x load");
    };
    return this
})();

var y=(function(){
    this.load=function(){
        alert("this is y load");
    };
    return  this
})();

x.load();
y.load();


x.load 和 y.load 的执行结果都是alert(this is y load)

我的问题
为什么 x 访问 var y.load?我认为 bc 每个加载函数都包装在自己的自调用匿名函数中,它只能由相应的变量访问

此外,为了实现我想要的(让 .load() 在变量范围内),声明每个对象的最佳方法是什么。(我只需要每个 x 和 y 的 1 个实例)

我想在这些函数中坚持自我参与 bc,我计划让 jquery 文档准备好事件处理程序,我想立即设置。

4

2 回答 2

0

自调用函数只会为您提供一个一次性范围,这将允许您创建闭包或仅使用变量而不会污染全局对象。'this' 不受影响。您可能对构造函数/新运算符语法感到困惑,它将为此提供一个新值,因此具有您所寻求的行为:

var x = new function () {
        this.load = function () {
            alert("this is x load");
        }
    }();

var y = new function () {
        this.load = function () {
            alert("this is y load");
        }
    }();

x.load();
y.load();

. .

(为了记录,使用构造函数的正确方法宁愿是这个:

function Alerter(alerterName) {
    this.name = alerterName;
}

Alerter.prototype.load = function () {
    alert('this is ' + this.name + ' load');
};

var x = new Alerter('x');
var y = new Alerter('y');

x.load();
y.load();

)

于 2013-09-27T07:35:50.390 回答
-1

这不是范围,它是上下文,并且您没有 ax.load或 a y.load

的值this取决于您调用函数的方式。

如果你打电话foo.bar(),那么,里面barthis将是foo

如果您没有foo(例如bar()),那么 的值this将是默认对象。在浏览器中是window.

由于thiswindow在这两种情况下,this.load是相同的。

可能您想使用局部变量 ( )var load关键字new

于 2013-09-27T06:50:15.937 回答