Javascript Hoisting -
Javascript Hoisting -
quite interesting thing discovered me js learner, consider next code.
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 can utilize on("slide", {container: container}, function(event, args){...})) bind slide event , pass external info it. - explain why values returned 2 console.log different? wonder if technique technically sound replacement on approach?
first of all, amazed getting null container. want see logs if can post
secondly, here's explanation of why won't work, not of why null:
this has nil hoisting
you executing init function lib.init({ container: $("#container") });
at time attached function this.init = function (e) { ... gets executed value of e, may event, e defined , variable container gets value
whereas, in next code on 5th line,
var slider = $("#div1").slider( ... // u calling slider the slider function beingness called options, , 1 of options is:
slide: function () { // anonymous , execute later console.log(e.container); // not null console.log(container); // null } most important, in scope of slider function of library, beingness executed here, function attaching slide: ... has not been executed yet. will, when slide event happens when happens, nowadays value of container used if getting null, resetting container, in fiddle here yckart not null , same e.container
javascript
Comments
Post a Comment