Scope Issues With Setting Javascript Function - javascript

I am in a position where I need to "update" a function that exists in another javascript file. The file looks like this:
function jf(){
alert('1');
}
//call jf periodically
jf();
The second js file, which is loaded after looks like this:
console.log(jf);
console.log(window.jf);
var func=function(){
alert('2');
};
jf=func;
window.jf=func;
The first log successfully returns the original jf method, the second doesnt. The first set seems to set the local variable jf, and the second does basically nothing. Is there a way to achieve this functionality?

According to Javascript closures - behavior of overridden functions from the global scope
var done = and function done do basicaly the same thing. They will shadow the outer definition in the inner scope but they will not replace it on the outer scope.
This means you can only override your initial definition of function jf() if you are in the same execution context. Otherwise, replace function jf(){ ... with window.jf = function(){...
Also, running your tests in an inspector console might help.

First, use variables:
var jf = function () {
alert('1');
};
jf();
Then the second bit should work fine:
var func = function () {
alert('2');
};
jf = func;
jf();

Related

make function with selectors in jquery.ready global

I have a really simple function:
function loading (text, id) {
console.log("test");
$('#loadingsts').append('<div id="loader"></div>');
}
that is defined in a javascript file which is loaded with the html via:
<script src="js/loader.js"></script>.
I want to execute that function in another js file so I need to have the function be global, right?
If I execute is like this, the console.log() works but the but the append doesn't. If I put the function into a $(function() {}); it says loading() not defined.
I also don't want the function to be executed on loading but only when called.
How can i make it work.
I looked at these questions already but they didn't help
Question1
Question2
Question3
A method created outside any other method is global by nature. If you are creating a method inside another method, you can make it global by attaching it to the window object if you like, or another object that is global itself, in which case you'd have to access it by thatObject.yourMethod()
var objectOutsideAnyMethod = {};
(function(){
function ImNotGlobal(){}
window.IAmGlobal = function() {};
objectOutsideAnyMethod.meToo = function(){};
})();
IAmGlobal(); //valid
objectOutsideAnyMethod.meToo(); //valid
ImNotGlobal(); //error

jQuery setInterval() undefined function error

Hi I am relatively new to javascript and jQuery and while trying to create a function the runs in intervals of 100 milliseconds I encountered a problem.I seem to get in the console of firebug and error witch says that clasing() is not defined.This is my code:
$(document).ready(function() {
var prev = $("img.selected").prev();
var curent = $("img.selected");
var next = $("img.selected").next().length ? $("img.selected").next() : $("img:first");
$("img").not(":first").css("display","none");
function clasing() {
curent.removeClass("selected");
next.addClass("selected");
}
setInterval("clasing()",100);
});
What am I doing wrong here?Thank you
You have a scope problem. Your variables (prev, curent and next) are accessible inside .ready scope, such as your function clasing. But when you add this function to be called in a interval, using setInterval, this function should be in a Global scope (inside window object). Then, you should declare this function like window.clasing = function(){ ... }, but, doing this, the variables declared in .ready() scope will not be accessible running the function outside this scope, so all your variables must be in a global scope too. This should solve your problem.
However, this isn't a good programming practice, you should declare your variables inside clasing function, then they will be accessible only in function scope; And your function must be delcared outside .ready() function, and then you declare the interval inside .ready() function.
So, your code should be liek this:
function clasing(){
var prev = $("img.selected").prev();
var curent = $("img.selected");
var next = $("img.selected").next().length ? $("img.selected").next() : $("img:first");
curent.removeClass("selected");
next.addClass("selected");
}
$(document).ready(function() {
$("img").not(":first").css("display","none");
setInterval("clasing()",100); //or just setInterval(clasing,100);
});
Change setInterval("clasing()",100); to setInterval(clasing,100);
Change
setInterval("clasing()",100);
To
setInterval(function() {
clasing();
}, 100);
Right now your call to setInterval is running in global scope, but your function is defined inside your jquery function. Creating a closure will give you access to the jquery functions members.

Calling function inside a variable

I am using a plugin JS and need to call a function in it.
It is having functions inside a variable like,
var win = window;
var Page = function(pageOptions, callback) {
function abc(){
--------
}
function xyz(){
------
}
};
win.Sales = {
Page: Page
};
Now, I need to call a function abc(). How can I call it.
Already tried with win.Sales.page.abc();.
Please help me out on this. Thanks in advance.
You cannot do that with your configuration because the functions are local or private.
You should make them accessible globally like:
var Page = function(...) {
...
};
Page.abc = function() {
...
};
That way, abc is a property of Page, and you can then access it like Page.abc and execute it like Page.abc(). Functions are basically also objects so they can have properties too.
You cant call function abc since it is declared as a private member of the function referenced by variable Page.
If you want to call the function You have to make it as a property of the variable Page.
var Page = function(){
.........
.........
.........
}
Page.abc = function(){
}
But there is another problem of variable scoping like if there is another variable x defined in function Page and used inside function abc, it will not work.
Anyway since you've said it is a js plugin I do not think it will be possible for you to change the function Page. So the answer will be No you cannot do that.

How do undefined or remove a javascript function?

I defined a global Javascript function:
function resizeDashBoardGridTable(gridID){
var table = document.getElementById('treegrid_'+gridID);
.....
}
After this function was used a few times, I want to remove(or undefined) this function because the Procedure code should be called again. if somebody try to call this method we need do nothing.
I don't way change this function right now.
so re-defined this function may be one way:
function resizeDashBoardGridTable(gridID){
empty,do nothing
}
Thanks. any better way?
Because you're declaring it globally, it's attached to the window object, so you just need to redefine the window function with that name.
window.resizeDashBoardGridTable = function() {
return false;
}
Alternately you could redefine it to any other value or even to null if you wanted, but at least by keeping it a function, it can still be "called" with no detriment.
Here's a live example of redefining the function. (thanks TJ)
An additional reason for pointing out that I'm redefining it on the window object is, for instance, if you have another object that has that function as one if its members, you could define it on the member in the same way:
var myObject = {};
myObject.myFunction = function(passed){ doSomething(passed); }
///
/// many lines of code later after using myObject.myFunction(values)
///
/// or defined in some other function _on_ myObject
///
myObject.myFunction = function(passed){}
It works the same either way, whether it's on the window object or some other object.
how about using a var?
// define it
var myFunction = function(a,b,c){
console.log('Version one: ' + [a,b,c].join(','));
}
myFunction('foo','bar','foobar'); // output: Version one: foo,bar,foobar
// remove it
myFunction = null;
try { myFunction(); console.log('myFunction exists'); }
catch (e) { console.log('myFunction does not exist'); }
// re-define it
myFunction = function(d,e,f){
console.log('Version two: ' + [d,e,f].join(','));
}
myFunction('foo','bar','foobar'); // output: Version two: foo,bar,foobar
OUTPUT:
[10:43:24.437] Version one: foo,bar,foobar
[10:43:24.439] myFunction does not exist
[10:43:24.440] Version two: foo,bar,foobar
The simplest approach is to set the function (treat it as a variable) to null. This works even if you don't declare it as a var. Verified this on IE.
resizeDashBoardGridTable = null
If the functions needs to be called 1 time you use an anonymous self invoking function like this:
(function test(){
console.log('yay i'm anonymous');
})();
If you have to call the function multiple times you store it into a var and set it to null when you're done.
Note: You don't have to name an anonymous function like I named it test. You can also use it like this:
(function(){
console.log('test');
})();
The reason I do name my anonymous functions is for extra readability.

call a specific javascript function when multiple same name function are in memory

I need to call specific js function. The problem is many time runtime situation can come where another js file may contain same name function. But i need to be specific that which function i am suppose to call.
Function overloading is not my solution.
Thanks and regards,
Tanmay
you're going to have to do some reorganization of your resources and use namespacing where you can.
if you have a method named saySomething defined twice, you would move one of them to an object (whichever suits your needs better).
var myNS = new (function() {
this.saySomething = function() {
alert('hello!');
};
})();
and the other defintion can be moved into a different object or even left alone.
function saySomething() {
alert('derp!');
}
you can now call the saySomething method like
saySomething(); // derp!
myNS.saySomething(); // hello!
edit: since it was brought up in comments, this
var myNS = {
saySomething: function() {
alert('hello!');
}
};
is equivalent to the first code block, in simpler form (if i'm remembering correctly).
At least in firefox, when you have two functions with the same name, the second will overwrite the first one.
So, you can't call the first one.
Try it:
function a() {alert(1);}
function a() {alert(2);}
a(); // alerts '2'
See in jsfiddle.
In javascript, similarly named functions automatically override previous function defined with the exact same name.
Let's say your page includes 1.js and 2.js and both of them define the same function, for example say, display(). In this case, based on which js file is included the last, the definition of 'display()' in that file will override all other prior definitions.
I use function scope to limit the scope of variables and functions
Here is an example:
// existing function in JavaScript
function one() {
console.log('one');
}
one(); // outputs one
// inserting new JavaScript
(function() { // anonymous function wrapper
'use strict'; // ECMAScript-5
function one() {
console.log('two');
}
one(); // outputs two
})(); // end of anonymous function
one(); // outputs one
I hope that helps
:)

Categories

Resources