(function () {
pm.view.functionName= function () {
function nameFunction() {
var something;
return something;
}
return win;
};
})();
I am in another JS file and i want to call this nameFunction()... how can i do this. I tried...
pm.view.functionName().nameFunction()
But i get an error called, cannot call function in the Object. How can i access the functions from other JS files.
The function nameFunction exists in the scope of the function functionName. You cannot access it from outside that function.
If you want to do so, you'll have to explicitly say so:
pm.view.functionName.nameFunction = function() {
var something;
return something;
};
You could then access it as pm.view.functionName.nameFunction().
nameFunction is local to pm.view.functionName and you cannot access it, just like you cannot access local variables. You can call nameFunction() only when being inside pm.view.functionName.
Related
I've the following javascript code
var globalConfiguration = null;
function loadFile(filePath) {
}
function onLoadPage() {
}
function getConfiguration() {
}
function process() {
}
I want to use IIFE to encolose all my functions in a closure to avoid cluttering the global name space,so I wrote :
(function(window){
var globalConfiguration = null;
function loadFile(filePath) {
}
function onLoadPage() {
}
function getConfiguration() {
}
function process() {
}
});
However, I do not understand this notion very well, now in my HTML page how would I call my function onLoadPage?
You can't without putting it in the global namespace somehow.
My recommendation to structure code like this:
function ExampleHelper() {
(function(scope) {
scope.globalConfiguration = null;
scope.loadFile = function(filePath) {
};
scope.onLoadPage = function() {
};
scope.getConfiguration = function() {
};
scope.process = function() {
};
})(this);
}
var foo = new ExampleHelper(); // "foo" now contains all of your functions
foo.onLoadPage();
Now that you have enclosed the module, you need to decide what you want to expose to the outside world. Anything you want to expose, you can export. Also, you need to decide what context (in this case, window) that you want to attach to. Then pass the context in right away (thus completing the IIFE).
For example:
(function(window){
var exports = {};
var globalConfiguration = null;
function loadFile(filePath) {
}
function onLoadPage() {
}
function getConfiguration() {
}
function process() {
}
exports.getConfiguration = getConfiguration;
window.myModule = exports;
})(window);
Attaching to the passed in window object is one way to export things out in a controlled fashion. So, you do need to pass the context (in this case window) to the IIFE. Perhaps, window will not always be the context for the call.
After running this code, myModule will be available on the global scope.
You can set your function to window.onload callback.
(function(window) {
var globalConfiguration = null;
window.onload = onLoadPage;
function loadFile(filePath) {}
function onLoadPage() {
alert('hello world');
}
function getConfiguration() {}
function process() {}
}(window));
This is called chaining of functions/methods and is usually done for better readability of the code and to avoid the usage of temporary variables to hold the return value of each function.
Check this post on chaining methods which helped me to understand the chaining better.
I see you wanted to use closures to avoid cluttering the global object. However, do note that we write functions for reusability. Though you create a closure, ensure that your methods inside the outer function are abstracted such that they can be used by other parts of the code.
For ex: from your code, you have a loadFile method which could be reused.
Now to see how you can use the methods you described in a chain.
Assumptions: (since i don't know why you wrote those methods, i am making some assumptions).
loadFile(filepath) - returns a file object
onPageLoad() - once the page is loaded, it returns the object or id of the input file
getConfiguration() - gets the file path
process() - process the file
onPageLoad().loadFile(getConfiguration()).process();
The important part is that the scope of the object is set correctly in the chaining. In order to do this, each method must return the reference to appropriate object.
Hope this helps.
Hey guys am a bit confused in running a function from the other. What I have tried is:
var a = (function() {
var babe = function() {
console.log('yay');
};
})();
When I run the code like a.babe() it gives me error like TypeError: Cannot read property 'babe' of undefined. Why is it happening like this?
I want to call the function babe from a ... How can i do it?
I hope you guys can help me ...
Thanks in advance.
You are creating a function called babe and it stays only within the scope of the immediately invoked function expression (IIFE) surrounding it. And since you are not returning anything to the caller, by default, the function call will be evaluated to undefined and that will be stored in a. That is why you are getting the error,
TypeError: Cannot read property 'babe' of undefined
It means that, you are trying to access a property called babe on an undefined value. In this case, a is undefined.
Instead of all this, you can simply return the babe function from the IIFE, wrapped in an object, like this
var a = (function() {
return {
babe: function() {
console.log('yay');
}
};
})()
Now, that the returned object is assigned to a, you can invoke babe function like this
a.babe();
babe is a local variable to the IIFE in that code. It isn't returned. It isn't a property of anything. It isn't accessible.
You have to expose it publicly if you want it to call it from outside that function.
var a = (function() {
var babe = function() {
console.log('yay');
}
return babe;
})();
a();
var a = (function() {
var babe = function() {
console.log('yay');
}
return {
"babe": babe
};
})();
a.babe();
Why have you made a a self executing function? What you want to do is to make a function babe part of an Object a for that, simply do this:
var a = {
babe: function() {document.write('yay');}
}
a.babe();
I have made an object a and added a function babe inside it.. then used the dot notation to access the function inside object a
To use your code you must do
var a = (function() {
var babe = function() { console.log('yay'); }
return babe
})();
a();
To make it a.babe() look at #thefourtheye or #Quentin.
The dot syntax is used to access a "property" of an object. So, in a simple example, you could use something like:
var a = {
babe: function(){ console.log('yay') }
};
a.babe(); // yay
In the case of your example, if you want to create a closure to hide other variables and functions from the global scope, you have to return an object that will then get assigned to a:
var a = (function() {
return {
babe: function(){ console.log('yay') }
}
})();
a.babe(); // yay
Just remember, anytime you use a dot, the variable in front HAS to be an object.
function shortUrl () {
$['post']('http://tinyurl.com/api-create.php?url=http://json-tinyurl.appspot.com/', function (a) {
});
};
I Want to make this function as a var so I can use shortUrl Anywhere in my script. Like
var shortaddress = shortUrl ();
I want to use the result in next function.
function shortUrl () {...}
is equivalent to
var shortUrl = function () {...};
So, it is already a variable.
A function is already a variable, so you can use it as such. For instance:
function foo() {
// ...
};
is more or less the same as
var foo = function() {
// ...
};
Basically, if you drop the parentheses and arguments (foo instead of foo()), you can use any function as a normal variable.
Therefore you can for instance assign it to other variables, like you normally would:
var bar = foo; // note: no parentheses
bar(); // is now the same as foo()
Or you can pass it as an argument to another function:
function callFunc(func) {
func(); // call the variable 'func' as a function
}
callFunc(foo); // pass the foo function to another function
If you want to use the shortUrl function anywhere, it must be declared in global scope. Then that variable becomes a property of Window object. For example the following variables
<script type="text/javascript">
var i = 123;
function showA(){ alert('it'); window.j = 456; }
var showB = function() { alert('works'); var k = 789; this.L = 10; }
</script>
are declared directly in Window object and so become its attributes. Thus now they can be easily accessed from any script. For example all the following commands work:
<script type="text/javascript">
alert(i); alert(window.i);
showA(); window.showA();
showB(); window.showB();
alert(j); alert(window.j);
alert(new showB().L); // here the function was called as constructor to create a new object
</script>
Functions in javascript are objects and so they can hold attributes in themselves.
In the example above you can consider the k variable to be a private property and the L variable a public property of the showB object(or function). And another example: if you include jQuery library in your page, jQuery usually exposes itself as window.jQuery or window.$ object. Just it's generally recommended to use global variables very sparely and carefuly to prevent possible conflicts.
Hi I have a few custom functions wrapped in jQuery's document.ready function. Most of these functions are utilized from within that function and work, but there is a case where I would like to access a function contained within this from the global scope. How can I do this? can i do something like:
jQueryReadyScope.myFunctionName('paramaters');
Thank you very much.
Nope, but you can name the function and pass it to .ready():
var myFunctionName = function (params) {
// do things
}
// pass as callback to ready function
jQuery(document).ready(myFunctionName);
// access directly like any other function:
myFunctionName('paramaters');
That's a scope issue, and all you need to do is specify the namespace. In this case, you're talking global so we'll use window.
window.myFunction = function() { ... stuff }
To access it from the global scope it would need to be assigned to a global variable, either by declaring it outside your document ready or by assigning it as a property of window:
var yourGlobalFunction1 = function() { ... }
$(document).ready(function() {
function privateFunction() { ... }
window.yourGlobalFunction2 = function() { ... };
yourGlobalFunction1();
privateFunction();
yourGlobalFunction2();
});
yourGlobalFunction1();
// and then at some later point AFTER the document ready has run,
// e.g., in response to some event:
$("#someelement").click(function() {
yourGlobalFunction2();
});
How can i call a YUI function that is wrapped inside a YUI().use from javascript?
example
Below is a YUI function "runShowAnim" which executes animShow.run(); for an animation effect...
var runShowAnim = function(e) {
animShow.run();
};
I want this effect to happen when i validate something in a javascript function. I tried to call it as below. But it doesn't seem to work.
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim();
}
I achieved this by sandwiching the YUI function completely inside a function and calling that function..
var runShowAnim = function() {
YUI().use('anim', 'node', function(Y) {
var animShow = new Y.Anim({
node: '#msgArea',
to: { height: 50,opacity:1 }
});
animShow.run();
});
};
now i can call runShowAnim without any problem like in the below sample function..
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim();
}
If you want to call a function, you have to suffix the function name with () and include 0 or more comma separated arguments between them.
runShowAnim();
If the function doesn't have global scope (as yours will have if it is declared inside a function passed to use()) and not passed outside in some way then you can only do this from the same scope.
I think you're missing the parentheses.
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim(); // right here
}
YUI.thefunction()?
I think you need to call it with namespace too
something similar to
var X = function(){};
X.Y = function(){};
X.Y.Z = function(){};
X.Y.Z.foo = function(e){alert(e);}
//foo("me");<-error
X.Y.Z.foo("me");
If you want to call a function that has been defined inside the closure (the function passed as the last parameter to YUI.use) from outside it, you need to expose the function globally.
Either define a global variable outside the closure and assign your function to it, or assign your function to the window object
i.e.
var runShowAnim;
YUI().use(function(e){
runShowAnim = function(){alert('called');}
});
runShowAnim();