作为一个JS学习者,我发现了一件很有趣的事情,考虑下面的代码。
this.init = function (e) {
var container = e.container;
// slider
var slider = $("#div1").slider({ orientation: "horizontal", step: 1,
slide: function () {
console.log(e.container); // not null
console.log(container); // null
}
});
};
它是这样称呼的:
lib.init({ container: $("#container") });
我知道我可以使用 on("slide", {container: container}, function(event, args){...}))
绑定(bind)幻灯片事件并将外部数据传递到它。但是 - 谁能解释为什么两个 console.log 返回的值不同?另外我想知道该技术是否是 on
方法的技术上合理的替代品?
最佳答案
首先,令我惊讶的是您为 container
获取了一个 null
。如果您可以发布,实际上想查看您的日志
其次,这里解释了为什么这行不通,但不是为什么你得到一个null
:
这与吊装无关
您正在使用 lib.init({ container: $("#container") });
执行 init
函数
此时附加函数 this.init = function (e) { ...
以 e
的某个值执行,可能是一个 Event
,所以e
被定义,变量container
得到一个值
然而,在第 5 行的以下代码中,
var slider = $("#div1").slider( ... // u are calling slider
正在使用选项调用 slider
函数,选项之一是:
slide: function () { // anonymous and will execute later
console.log(e.container); // not null
console.log(container); // null
}
- 最重要的是,您处于库的
slider
函数的范围内,因为它正在执行 - 在这里,您附加到
slide: ...
的函数尚未执行。它会在slide
事件发生时 - 发生这种情况时,将使用
container
的当前值
如果你得到一个null
,肯定是有东西在重置container
,就像 fiddle here by yckart 它不为空并且与 e.container
关于Javascript 提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14755554/