[英]Javascript Hoisting
Quite an interesting thing was discovered by me as a JS learner, consider the following code. 作为一名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
}
});
};
here's how it's called: 这是怎么称呼的:
lib.init({ container: $("#container") });
I know that I can use on("slide", {container: container}, function(event, args){...}))
to bind slide event and pass external data into it. 我知道我可以使用on("slide", {container: container}, function(event, args){...}))
绑定幻灯片事件并将外部数据传递给它。 But - could anyone explain why values returned by two console.log are different? 但是-谁能解释为什么两个console.log返回的值不同? Also I wonder if the technique is a technically sound replacement for on
approach? 也不知该技术是一个技术上可行的替代on
方法呢?
First of all, I am amazed that you are getting a null
for container
. 首先,我很惊讶您获得container
的null
。 Would actually want to see your logs if you can post 如果可以发布,实际上会希望查看您的日志
Secondly, here's an explanation of why this won't work, but not of why you get a null
: 其次,这是为什么不起作用的解释,而不是为什么您得到null
:
This has nothing to do with hoisting 这与起吊无关
you are executing the init
function with lib.init({ container: $("#container") });
您正在使用lib.init({ container: $("#container") });
执行init
函数lib.init({ container: $("#container") });
At that time attached function this.init = function (e) { ...
gets executed with some value of e
, may be an Event
, so e
is defined and the variable container
gets a value 当时附加的函数this.init = function (e) { ...
以某个e
值执行,可能是Event
,因此定义了e
并且变量container
获取了一个值
Whereas, in the following code on 5th line, 而在第5行的以下代码中,
var slider = $("#div1").slider( ... // u are calling slider
the slider
function is being called with options, and one of the options is: 使用选项调用 slider
功能,选项之一是:
slide: function () { // anonymous and will execute later
console.log(e.container); // not null
console.log(container); // null
}
slider
function of your library, as it is being executed 最重要的是,您正在执行库的slider
功能范围内 slide: ...
has not been executed yet. 此处,您要附加到slide: ...
的功能slide: ...
尚未执行。 It will, when slide
event happens 发生slide
事件时会 container
will be used 发生这种情况时,将使用container
的现值 If you are getting a null
, something definitely is resetting container
, as in the fiddle here by yckart its not null and is same as e.container
如果你得到一个null
的东西肯定是重置container
,如小提琴这里通过yckart它不是null,而是同e.container
看不到区别...对我来说,两个logs
相等: http : //fiddle.jshell.net/WJ2s8/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.