Access a global var - javascript

I have a situation like this one:
talenti = $(".talenti");
filtra = $(".filtra");
wrapNavHeight = $("#wrapNav").outerHeight(true);
filtra.click(function(e) {
e.preventDefault();
$(".nasco").hide();
$("#sliding-navigation").delay(delay).show();
delay += 500;
talenti.removeClass('opened');
filtra.addClass('opened');
filtra.attr('id',"focF");
talenti.attr('id',"");
if (filtra.hasClass("opened")) {
$("#wrapNav").slideToggle("100", "linear", function(){
alert(wrapNavHeight);
$("#container").animate({"height": "+=wrapNavHeight"}, 100,function(){
$(".box").animate({"top": "+=wrapNavHeight"});
});
});
}
});
I am trying to get wrapNavHeight but alert(wrapNavHeight); outputs null; can't then assign that value to the next animate lines
Anyone?

isn't it just that you are assigning the variable the value of outerHeight at the time it's not visible? I think you need to re-evaluate outerHeight after the toggle transition. Replace
alert(wrapNavHeight);
with
alert($("#wrapNav").outerHeight(true));
see if that's any better?

Nobody else actually explained why this happens. Here's why:
It depends on:
which object is used as "this" for invocation of the function containing all the code above
which object is used as "this" for invocation of the function defined starting on line 4 of your code
In JavaScript, "global" references actually apply to the current this object (or to the "true" global object (window in web browsers) if not within a function)
Thus, if the this objects for the 2 functions I pointed out above are different, then you'll get the situation you observed.
In the browser, the default this object is usually window, but this can be changed when the function is run, such as by passing a different parameter to apply or by calling the function as a method.
Been a year since I used jQuery seriously, but if I recall right, jQuery event handlers usually rebind this to something useful related to the event (using apply-- you can do this too).
So, assuming the outer function's this hasn't been bound to anything special other than window, simply replace wrapNavHeight with window.wrapNavHeight in the inner function to achieve your desired effect.
(In practice I wouldn't actually do this, though, as a matter of style. Just declare wrapNavHeight as a var within the outer function instead, and then you'll get lexical scoping.)

Try searching.
jQuery global variable best practice & options?

Related

Why is aliasing 'this' in JS so bug prone?

Reading Principles of writing consistent, idiomatic JavaScript in the section titled "Faces of this" it suggests that aliasing this in JavaScript is "extremely bug prone".
I personally try to use _.bind() (or something similar) whenever possible but does anyone know why aliasing this is so error prone?
There are four meanings this can take dependending on how it was invoked. Accordingly care must be taken to keep track of which this is being used, and I can think of this-prone problems in at least 3/4 of them.
Invoked as method
In obj.myFunc(), this binds to obj.
This one can be scary if myFunc is passed in a callback, as it will forget that it was once part of an object and be invoked standalone. See e.g. What does 'var that = this;' mean in JavaScript? for the usual workaround to this.
Invoked as standalone function
In plain myFunc(), this binds to global object.
Invoked as constructor
Invoked as new myFunc() (very different! All functions that are intended to be invoked with new should be capitalized, thereby looking like a pseudoclass). Creates a new object, binds it to this and (probably) returns that object.
Of course if you drop the new you will bind to the global object, which will likely clobber a lot of stuff and leave your program in a very broken state. The capitalization convention is very important, and lets this problem be picked up by JSLint (IIRC).
Invoked with apply (or call)
Invoked as myFunc.apply(obj, args), in which this binds to obj. Note this has security implications even, as any caller can swap out this with its own spoofed object.
this being aliases everywhere would be bug prone because it gets rather difficult (for the developer) to remember exactly what this is referring to in a given situation. This can easily lead to a developer using this believing it refers to one element, when in reality it is something totally different. For example:
$('#something').click ( function (e) {
//this refers to the clicked element
var _this = this; //Tracking a reference to the clicked element `this`
$.each(someArray, function(index, value) {
//this refers to the current element being iterated in someArray
$.ajax({
url : 'some/path',
success: function (res) {
//this refers to the ajax request
//_this still references the clicked element
}
})
})
})
Furthermore, if you need to access one this from within the scope of another this (for instance this clicked element from within the ajax call) you have to keep a reference to it somehow. I have marked this in the code.

"this" does not refer to the this-reference using prototype [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
Today I ran into a very odd problem using Javascript's prototype and the this reference.
Basically, I have two objects. One object makes use of a div element and makes is possible to register an onclick event on the div. The other object makes use of this functionality and registers the onclick event using the first object.
Here is the code:
My first object, which takes care of the div:
DivObject = function() {};
DivObject.prototype.setClickListener = function(clickListener){
document.getElementById("myDiv").onclick = function(e){
clickListener(e);
};
};
My second object uses this functionality:
MainObject = function(){
this.myString = "Teststring";
this.divObj = new DivObject();
this.divObj.setClickListener(this.handleClick);
};
MainObject.prototype.handleClick = function(e){
// do something with e
};
The problem is, that inside MainObject.prototype.handleClick, the this reference refers to the window object, not to the MainObject. So, console.log(this) inside this function logs [Object window].
You can see this behaviour on jsfiddle.
As a workaround, I use the setClickListener function as follows:
var thisRef = this;
this.divObj.setClickListener(function(e){
thisRef.handleClick(e);
});
Now, the this reference in my handleClick function refers to my MainObject (as I want it to be).
See this workaround on jsfiddle.
My questions are:
Why does the this reference one time refer to the window object and one time to the this reference of my object? Is it overridden somewhere? I always thought using this in my object I can be sure that it is really the this reference of my object? Is the workaround I am using now the way how this problem should be solved or are there any other, better way to handle this case?
Your questions:
Why does the this reference one time refer to the window object and one time to the this reference of my object?
Other than using bind, the value of a function's this is set by how the function is called. When you do:
this.divObj.setClickListener(this.handleClick);
you are assigning a function reference, so the function is called later without any qualification (i.e. it's called as just handleClick rather than this.handleClick). On entering the function, because its this isn't set by the call, it will default to the global (window) object, or in strict mode remain undefined.
Is it overridden somewhere?
No, the value of this is set on entering an execution context. You can't overwrite it or directly assign to it, you can only set it in the call (e.g. as a method of an object, using new, apply, call) or using bind (also, arrow functions adopt the this of their enclosing lexical execution context).
I always thought using this in my object I can be sure that it is really the this reference of my object?
At the point you make the assignment, this is what you expect. But you are assigning a reference to a funciotn, not calling the function, so its this isn't set at that moment but later when it's called.
Is the workaround I am using now the way how this problem should be solved or are there any other, better way to handle this case?
Your work around is fine (and a common fix), it creates a closure so may have minor memory consequences but nothing serious. For very old versions of IE it would create a memory leak due to the circular reference involving a DOM object, but that's fixed.
The bind solution is probably better from a clarity and perhaps maintenance viewpoint. Remember to include a "monkey patch" for browsers that don't have built–in support for bind.
Please post code on SO, there is no guarantee that code posted elsewhere will continue to be accessible. The work around code:
MainObject = function(){
this.myString = "Teststring";
this.divObj = new DivObject();
var thisRef = this;
this.divObj.setClickListener(function(e){
thisRef.handleClick(e);
});
};
You could fix this by using .bind():
this.divObj.setClickListener(this.handleClick.bind(this));
See the demo.

JavaScript passing arguments to button onclick functions

I'm trying to create a bunch of buttons via loop, and use the loop iterator as an argument for each of the button onclick functions.
My code:
var testFnc = function(i) { alert("Arg: " + i); }
mainDiv.append(create_button(name, "buttonCSS", testFnc(i)));
However the functions are called automatically as the page loads and the buttons are placed (i.e. I see the alerts right away).
I'm sure there's some common design pattern for this.
Thanks!
One approach is to, for each button, call a "self-executing" function that creates a separate function.
mainDiv.append(create_button(name, "buttonCSS", (function(i) {
// For the function below, i comes from
// this function's scope, not the outside scope.
return function() {
testFnc(i);
};
})(i) ));
This will allow you to change the value of i outside the function and leave existing buttons unaffected.
(If you are creating a lot of buttons (perhaps thousands), it might be better to change the create_button function to add a property to the button element itself and have your function check that. Or if your code does not need to work in Internet Explorer 8 or below, you can use the bind() function instead of the above code.)
Note: for a very detailed explanation of this, please see my previous answer to an identical question.
By using parentheses, you're calling testFnc and passing its return value to the create_button function, so of course it alerts right away. Instead, you need to pass in an actual function object without invoking it. Do this by wrapping testFnc in an anonymous function, ala function() { testFunc(i); }. Can you see how this returns a function that will be run later rather than immediately?
This by itself still won't work, since i participates in a closure around it, so that when the click event runs it uses the most recent value of i (the value it was at the end of the loop), rather than the one at the time of binding. To fix this, create a new closure around a different variable—positioned only in the immediate scope of your callback and no higher—that will be given the value of i so that the click event has the value as of the time of binding, not the time of execution of the bound function.
Here's how to do this:
for (i = 0; i < len; i++) {
mainDiv.append(
create_button(name, "buttonCSS", (function(val) {
return function() {
testFnc(val);
};
}(i)))
);
}
I'm sure that looks a bit confusing, but the point is that wrapping the function that is called (the one that is returned) in another function creates a new scope with a variable val that isn't used in any outer function. This makes the closure only over the immediate value, detaching it from i, which is what you want. There is a deeper explanation of this here.
Please note that one other answer on this page reuses i which could be confusing. That will work, but then it is unclear inside of the inner function which i is being referred to! I think it is better practice to avoid any confusion by using a different variable name.
Are you using jQuery? You could reference the class of a button
<button class='my-custom-class' data-index='0'>This button</button>
and in document.ready:
$(document).ready(function () {
buildButtons();
$('.my-custom-class').on('click', function () {
var index = $(this).attr('data-index');
alert('Arg: ' + index);
});
});
I suggest using a custom data-* attribute since you can use the attr property in jQuery to access the custom attribute. This is one way you could implement it.

Dynamically superseding functions that are not in global scope

I have a script, that based upon specific scenarios, may need to supersede functions to do some processing before eventually calling the original function. (See "'overriding' Javascript Function")
I can get this working in general - here's a basic example using the jQuery plugin Tinyscrollbar (not my intended application, just something quick and easy to illustrate):
(function ($) {
// Snip..
function initalize() {
oSelf.update();
setEvents();
return oSelf;
}
// Snip..
function setEvents() {
(function () {
var oldInit = wheel;
wheel = function (oEvent) {
console.log('Intercept');
oldInit(oEvent);
}
})();
// Original event code, irrelevant to question
}
function wheel(oEvent) {
// Actual function, related to using the mousewheel
}
})(jQuery);
When I scroll the mousewheel, the console prints 'Intercept', and the scrollbar moves as originally defined. Wonderful!
However, the function name is hardcoded, and doesn't live in the global scope, so window[] is unavailable (which I like). Is there any possible combination of black magic, 'new Function()', and/or other way to loop through a potential list of function names (which may change based on other logic) and encapsulate them in this (or similar-in-spirit) manner?
Thanks in advance!
Unfortunately, there's no way to enumerate or dynamically access members in a scope object (with the convenient exception of the global scope/window object)
So you'd need to rephrase your code a bit. Instead of having free-floating functions in your outer function, have objects with methods on them. That'd make replacing those methods much easier.
There's some additional trickiness if you modify your functions after you started assigning them as event handlers or whatever. If you happen to use some kind of bind() wrapper around those functions, the correctness of your behavior will depend a lot on that bind() function.
Specifically, if you want the replacement method to retroactively become the method called for any event handler or callback it was assigned to, you'll want to use a bind() wrapper that takes a context object and a string meant to be the function name rather than a context object and a function reference. (and make sure that bind() doesn't resolve that string early to shave some ms on each calls.)
If don't don't want the retroactive behavior, you still have to make sure you don't have some bind()-ed version of the original method floating around and still being used for new callbacks after your replacement happened.

Benefit of using 'window' prefix in javascript

Are there any benefits to using the 'window' prefix when calling javascript variables or methods in the window object? For example, would calling 'window.alert' have an advantage over simply calling 'alert'?
I can imagine using the prefix could give a small performance boost when the call is made from inside some function/object, however I rarely see this in people's code. Henceforth this question.
This is useful when attempting to test global object values. For example, if GlobalObject is not defined then this throws an error:
if(GlobalObject) { // <- error on this line if not defined
var obj = new GlobalObject();
}
but this does not throw an error:
if(window.GlobalObject) { // Yay! No error!
var obj = new GlobalObject();
}
Similarly with:
if(globalValue == 'something') // <- error on this line if not defined
if(window.globalValue == 'something') // Hurrah!
and:
if(globalObj instanceof SomeObject) // <- error on this line if not defined
if(window.globalObj instanceof SomeObject) // Yippee! window.prop FTW!
I would not expect to see a significant performance difference, and the only other reason you might do this is to ensure that you are actually getting a value from the global scope (in case the value has been redefined in the current scope).
I doubt there is any measurable performance benefit. After all the scope chain would be scanned for the identifier window first then the window object would be scanned for the desired item. Hence more likely it would be deterimental to performance.
Using window prefix is useful if you have another variable in scope that would hide the item you may want to retrieve from the window. The question is can you always know when this might be? The answer is no. So should you always prefix with window? What would you code look like if you did that. Ugly. Hence don't do it unless you know you need to.
Retrieved from Google (http://www.techotopia.com/index.php/JavaScript_Window_Object):
The window object is the top-level object of the object hierarchy. As such, whenever an object method or property is referenced in a script without the object name and dot prefix it is assumed by JavaScript to be a member of the window object. This means, for example, that when calling the window alert() method to display an alert dialog the window. prefix is not mandatory. Therefore the following method calls achieve the same thing:
window.alert()
alert()
However, I read but have not had time to test the following from:
(http://www.javascriptref.com/reference/object.cfm?key=20)
One place you'll need to be careful, though, is in event handlers. Because event handlers are bound to the Document, a Document property with the same name as a Window property (for example, open) will mask out the Window property. For this reason, you should always use the full "window." syntax when addressing Window properties in event handlers.
As far as performance, I think AnthonyWJones has it covered.
One use of the window prefix is to explicitly make something available outside the current scope. If you were writing code in a self-invoking function to avoid polluting the global scope, but there was something within that you did want to make globally available, you might do something like the following:
(function(){
function foo(){
//not globally available
}
function bar(){
//not globally available
}
window.baz = function(){
//is globally available
foo();
bar();
};
})();
I imagine that the performance benefit here is amazingly insignificant at best, if there is one at all.
It only matters if you're using frames and doing a bunch of javascript calls across frames, and even then only specific scenarios warrant the necessity of referencing window explicitly.
When you use the prefix, you're making it explicit you're using the "global" definition of the variable, not a local one. (I'm not sure whether / how you can inject variables into a scope in JS, except the weirdness with this and inline event handlers.) YMMV, you may either prefer the clarity, or find it to be just clutter.

Categories