I am currently trying to learn javascript and what I want to achieve is to call a function, from outside the main function. For a better idea, I left the code which I am currently exercising on. I will be extremely grateful If someone can explain to me why exactly this function is not working. Thank you in advance.
function One_Main(){
function Alpha(){
console.log("Alpha");
}
}
One_Main();
function Two_Main(){
Alpha();
}
Two_Main();
Alpha() is in the scope of One_Main, you can't see it from the global scope. To call Alpha() from outside of One_Main you need to declare it outside of that function.
function Alpha(){
console.log("Alpha");
}
function One_Main(){
Alpha();
}
One_Main();
function Two_Main(){
Alpha();
}
Two_Main();
It's not working because Alpha is not visible outside of One_Main.
To make it visible, you can define One_Main as an object, then make Alpha a property of One_Main.
To fix your code, do this:
function One_Main() {
this.Alpha = function() {
console.log("Alpha");
}
}
// Make it visible
Alpha = new One_Main().Alpha;
function Two_Main() {
Alpha();
}
Two_Main();
ES2015 Style
class One_Main {
constructor() {}
static Alpha() {
console.log("Alpha");
}
}
// Make it visible
Alpha = One_Main.Alpha;
function Two_Main() {
Alpha();
}
Two_Main();
As a simple property in pure JS
function One_Main() {}
One_Main.Alpha = function() {
console.log("Alpha");
}
// Make it visible
Alpha = One_Main.Alpha;
function Two_Main() {
Alpha();
}
Two_Main();
You might want to read about scoping in javascript to understand the problem.
https://scotch.io/tutorials/understanding-scope-in-javascript
The function Alpha is not visible inside the Two_Main function
PS: Debugging is useful to learn more about the error. In Chrome you can right click and select Inspect element and look at the console to debug javascript.
Checkout https://raygun.com/blog/debug-javascript/ for more information
I dont know what tutorial are you studying, maybe you are reading about currying method, if that is the case, you can make:
function One_Main(){
function Alpha(){
console.log("Alpha");
}
return Alpha;
}
One_Main();
function Two_Main(){
One_Main()();
}
Two_Main();
Related
I am currently working on a project where I want to deference an array of functions (function references) and excecute the function.
This does only work, if I don't call another class method within the function.
Otherwise I get "Uncaught TypeError" and I can't figure out how to solve this error.
Here's my code sample 'working' the same way my original project does:
After calling function2 the engine cannot find this.log...
Do you have ideas? Thank you very much in advance.
KR, Robert
class ArrayWithFunctions {
constructor() {
this.functionTable = [
this.function1,
this.function2,
];
}
execute(index) {
return (this.functionTable[index])();
}
log(chars) {
console.log(chars);
}
function1() {
console.log('I am Function 1.');
}
function2() {
this.log('I am Function 2.');
}
}
let example = new ArrayWithFunctions();
example.execute(0);
example.execute(1);
This is an example of Javascript's execution contexts in action. In this situation, to avoid losing the correct reference to the class, you can bind the functions when putting them inside the array, or initialize them as arrow functions:
Example 1: Bind them in the constructor:
constructor() {
this.functionTable = [
this.function1.bind(this),
this.function2.bind(this),
];
}
Example 2: Create them as arrow functions:
class ArrayWithFunctions {
// ...
function1 = () => {
console.log('I am Function 1.');
}
function2 = () => {
this.log('I am Function 2.');
}
}
You can use arrow functions to dodge scoping issues:
function2 = () => {
this.log('I am function 2.');
}
Related: How to access the correct `this` inside a callback (and you might also want to take a look at How does the "this" keyword work?).
In this case you can simply set the correct this value by calling the function with .call:
return this.functionTable[index].call(this);
function chart(){
Barchart();
Linechart();
function Barchart(){
}
function Linechart(){
}
}
Chart() is main parent function. Inside I have two chart functions. I have to call only line chart.
Chart(); will execute both barchart and linechart.
but I need to call only line chart.
Yes, this is true. Both will execute in the order given. You need to provide some sort of selection. Either using an if/then or some other way.
If(myChecbox.isSelected){
barchart();}
else{
linechart();
}
Ask yourself, what is it that is making the choice? Let me know what you come up with. You will need to place the called functions outside of your method...as stated in the others post.
I know only object function can call for one specific function ..
var chart = {
Barchart : function(){
alert('');
},
Linechart : function(){
alert('');
}
}
chart.Barchart();
If you want the inner function to be executed,
function outer() {
function inner() {
alert("hi");
}
inner(); // call it
}
Hope this helps.
you should do this so that you have good control on your function calling or you directly Linechart also return instead of init
var chart = (function () {
var Barchart = function () {
console.log("bar chart");
};
var Linechart = function () {
console.log("line chart");
};
var init = function () {
Linechart();
}
return {
init: init
//you can retrun Barchart or Linechart which you want to access publically
}
})();
chart.init();
after your edit just remove the first call to Barchart()
You can't!
The scope of this functions is only the chart() function, so they are not accessible outside, unless you give them out from inside chart() somehow, like by returning them.
Although less common, nesting functions this way is possible. It's a method called currying. Your function Linechart() is scoped within chart(), so at the moment, it can only be called there. In order to make it available elsewhere, you'll need to place it out with the function so the scope is broadened. Something along the lines of:
function Linechart(){
alert("Line called!");
}
function chart(){
function Barchart(){
alert("Bar called!");
}
Barchart();
Linechart();
}
chart();
// Line chart on it's own
Linechart();
This will mean that when you call chart(), both Linechart() and Barchart() are called, but you'll also be able to call Linechart() on its own.
i hope these will be helpful.
function chart() {
function Barchart()
{
alert('Barchart');
}
function Linechart()
{
alert('Linechart');
}
Barchart();
Linechart();
}
chart();
Ok, I have being trying to find a solution for this for the past 3 hours...
I want to be able to create my own library, accessible function within function with function etc.
Here's what I want to do...
var outer=function()
{
this.inner=function()
{
this.innermost=function()
{
alert("innermost");
}
}
}
var outer=new outer;
function start()
{
//I want to call it like this but fails!
outer.inner.innermost();
}
Now this fails when I try to call the innermost. But if I just have a a function within a function, it works. For example:
var outer=function()
{
this.inner=function()
{
alert("inner");
}
}
var outer=new outer;
function start()
{
// this works
outer.inner();
}
All the examples I've found only show a function within a function.
I want to be able to create my own library of functions. With an easy way to access them, e.g.:
MyLib.SubLib.SubLib2.function
MyLib.SubLib.SubLib2.property
Any help on the matter would be greatly appreciated. Would I have to learn and use prototypes?
First of all, this is how you do it:
var outer = function() {
this.inner = {
innermost: function() {
alert("innermost");
}
}
}
var outer = new outer;
outer.inner.innermost();
The reason why it didn't work the way you did it is because you define a function inner - so outer.inner is a function. You could do var inner = new (outer.inner)(); and then call inner.innermost(); but that's obviously ugly and not what you want.
Ok, this may sound a bit crazy but hear me out :)
I would like to do the following in javascript:
define START_OF_EVERY_FUNCTION = "try {"
define END_OF_EVERY_FUNCTION = "} catch () {}"
function TEST () {
START_OF_EVERY_FUNCTION
// rest of function
END_OF_EVERY_FUNCTION
}
Basically, can I define a list of javascript lines (code) and include them as above? I'm looking for a technique versus comments about whether this is a good idea or not or debate over wrapping all functions in a try/catch block.
I know about eval(), but I dont think you can eval statements like the above.
This might be goofy but you could define a master function and run other functions through it by passing them in.
var execute = function(func){
alert('before');
func();
alert('after');
};
function sayHi(){
alert('hi there');
}
execute(sayHi);
As requested, an example with passing arguments.
var execute = function(func){
alert('before');
var ret = func.apply(null, Array.prototype.slice.call(arguments, 1));
alert('after');
};
function saySomething(sayWhat){
alert(sayWhat);
}
execute(saySomething,'hey there');
That is not allowed in JavaScript.
You could extend the Function prototype:
Function.prototype.tryThis = function() {
try {
this();
}catch(ex){
alert('Caught '+ex);
};
};
function tryIt() {
alert('Inside tryIt');throw "My Error from tryIt";
}
tryIt.tryThis();
You need to look into aspect oriented programming for JavaScript. You can create hooks for function entry and exit. Tools like JSUnit do this for example.
I think you can do this with the "new Function" operator. I've never used it myself, since I'm not clinically insane, but I believe you can pass it a string which it will evaluate and use as the function body. You can also get the code for each function by calling myFunction.toString(). So put together, it'd be something like this:
var functionsToMessUp = ['myFunc1', 'myFunc2'];
for (var i = 0; i < functionsToMessUp.length; ++i) {
var theFunc = window[functionsToMessUp[i]]; // assuming they're in global scope
window[functionsToMessUp[i]] = new Function(
START_OF_EVERY_FUNCTION
+ theFunc.toString()
+ END_OF_EVERY_FUNCTION
);
}
Now, the above almost certainly won't work - there's parameters and other things to take into consideration, and I don't even think that's how the new Function constructor works, but if you really want to go down this path (which I really don't recommend), then this might be a good starting point for you.
Maybe something like this?
function tryCatch(callback) {
try {
callback();
} catch() {}
}
var myFunction = function() {
// do some stuff
};
tryCatch(myFunction);
I haven't found a good reference for declaring my own functions inside the
jquery.ready(function(){});
I want to declare them so they are inside the same scope of the ready closure. I don't want to clutter the global js namespace so I don't want them declared outside of the ready closure because they will be specific to just the code inside.
So how does one declare such a function...and I'm not referring to a custom jquery extension method/function...just a regular 'ol function that does something trivial say like:
function multiple( a, b ){
return a * b;
}
I want to follow the jquery recommendation and function declaration syntax. I can get it to work by just declaring a function like the multiply one above...but it doesn't look correct to me for some reason so I guess I just need some guidance.
I believe that you would be okay just declaring the function inside the ready() closure, but here you can be a bit more explicit about the local scoping:
jQuery.ready(function() {
var myFunc = function() {
// do some stuff here
};
myFunc();
});
It might sound simple but you just ... declare the function. Javascript allows functions to have inner functions.
$(document).ready( function() {
alert("hello! document is ready!");
function multiply(a, b) {
return a * b;
}
alert("3 times 5 is " + multiply(3, 5));
});
I have a StartUp function, and I use it as printed bellow:
function StartUp(runnable)
{
$(document).ready(runnable.run);
}
var ExternalLinks =
{
run: function()
{
$('a[rel="external"]').bind('click', ExternalLinks.click);
},
click: function(event)
{
open(this.href);
return false;
}
}
StartUp(ExternalLinks);
var ConfirmLinks =
{
run: function()
{
$('a.confirm').bind('click', ConfirmLinks.click);
},
click: function(event)
{
if (!confirm(this.title)) {
return false;
}
}
}
StartUp(ConfirmLinks);
My web sites are modular, so every module has N actions and every action can have a .js file, so I just write function and call it with StartUp(...functionName...)