Say I want to do this:
function z(){return function(){a = 4}
}
function b(){
var a;
c = z();
c();
}
I want to skip the c(); But instead I want to execute the returned function immediatly upon return in the caller scope so I can work with it.
In this example a should get the value 4.
Is there a way?
cheers
You should be able to execute the return function immediately with
z()();
No, that is impossible (without using tricks like eval). You cannot change the scope of the function returned by z.
Your example could be simpler without the closure, what you are asking for is just
function c() {
a = 4;
}
function b() {
var a;
c(); // should change variable a
return a;
}
b(); // is expected to return 4, but does not
You can't alter the scopes of functions, or pass the scope objects (like pointers to the variables). Yet, you can pass an object whose properties will be altered by the function:
function z(obj) {
return function() {
obj.a = 4;
};
}
function b() {
var o = {};
z(o)(); // as mike and others said, this is the same as yours
// - you don't need the c variable
return o.a;
}
b(); // returns 4 now
escaparello did a similar thing, only he did use the object as the thisValue which he did pass to the anonymous function, not to z. I think mine is easier to understand, and makes a better use of the z closure.
Seems very strange, but you want to do something like this?
function z(){
return function() {
this.a = 4;
return this;
}
}
function b(){
var obj = { a : 0 };
var c = z().apply(obj);
console.log(c.a);
}
b();
Try this
function z(){
return function(){
return 4;
}
}
function b(){
var a;
a = z()();
}
Related
Function b is declared inside function a. So, i am trying to call function b outside function a. It is not getting called.
var a = function() {
alert("a");
var b = function() {
alert("b");
}
}
Output:-
function b called
Alert box with message b
You'd need to return b and use that. This will involve calling the function a to begin with, but then you'd have a function which you could call repeatedly to alert b:
var a = function() {
alert("a");
var b = function() {
alert("b");
}
return b;
}
var messageB = a();
messageB();
messageB();
First return that function and call it,
var a = function() {
alert("a");
var b = function() {
alert("b");
}
return b;
}
var b = a();
b();
Try to declare 'b' variable outside 'a' function:
var b;
var a = function() {
alert("a");
b = function() {
alert("b");
};
};
That way, you can access b from outside of a as it is declared outside of it. Before a was called the first time, it will be undefined though, so you can't call b before a. Additionally if you call a twice, the previous b will be overriden., as shown here:
var b;
var a = function(name) {
b = function() { alert(name); };
};
a("first version");
b(); // first version
a("second version");
b(); // second version
If you don't need any inner variables from a inside b, there is no reason to nest the functions though, in that case you should just have two independent functions:
var a = function() { alert("a"); };
var b = function() { alert("b"); };
As mentioned you can simply return function b. Functions in Javascript can be passed around like this, it's a very nice feature of a garbage collected language.
But you can go even better, what if you wanted to expose more than one function.
You can just return an object with methods attached.
function A() {
let value = 0;
return {
inc: () => ++ value,
dec: () => -- value,
show: () => console.log(value)
}
}
const a1 = A();
a1.inc(); a1.inc(); a1.show();
const b1 = A();
b1.inc(); b1.dec(); b1.dec(); b1.show();
Now the above looks very similar to what's called a class but it's not. One disadvantage to this is if you wanted to create thousands of instances, a class would be better as that can put it's methods on the prototype. But saying that, as has been found using React Hooks it's not really that bad then.
One big advantage of the above, is you don't have to get into the muddy world of this context of instances.
For completeness here is a class version.
class A {
value = 0;
inc() { ++ this.value; }
dec() { -- this.value; }
show() { console.log(this.value) }
};
const a1 = new A();
a1.inc(); a1.inc(); a1.show();
const b1 = new A();
b1.inc(); b1.dec(); b1.dec(); b1.show();
It was also said a simple solution is to make a and b both global, but the more you avoid the global the better, so if a and b have some common intent, using closures or even a class would be better.
or if you would need object approch
`var a = function() {
print("a");
this.b = function() {
print("b");
}
return this
}
a().b()`
All the other answer's are great enough, but just in case you may like this approach of directly calling inner function without returning that function.
You can simply wrap your inner function i.e b in your case, as a self invoking function like this,
var a = function() {
alert("a");
var b = (function() {
alert("b");
})()
}
Ref
If I need a object into another for use in a function, which is the best?
function A() {
this.alert = function () {
console.log(b.value);
}
this.alert2 = function () {
console.log(this.value);
}
}
function B() {
this.value = 'test';
}
var a = new A();
var b = new B();
A.prototype.b = b;
// Option 1
`a.alert();`
// Option 2
`a.alert2.apply(b);`
I believe option 2 is better because only use the object (b) in one function.
The prototype is much easier, but I'd use it the other way round:
function B() {
this.value = 'test';
}
B.prototype.alert = function() {
console.log(this.value);
}
var b = new B();
b.alert();
If you want to use a function/method of a different object, you should give it a parameter (instead of using an implicit global b variable like in your a.alert function):
var a = {
alert: function(x) {
console.log(x.value);
}
};
a.alert(b);
or inherit from it when you have a method, like:
var a = {
value: "a test",
alert: function() {
console.log(this.value);
}
};
// =============================
function B() {
this.value = 'test';
}
B.prototype.alert = a.alert; // mixin inheritance
var b = new B();
b.alert();
There isn`t a best option, its about what you have to do.
The first option by putting b in its prototype makes A to be more coupled to b.
The 2nd one you are changing its contests.. you need to know what the function does, if you don`t have the documentation you may pass an object wich doesnt has a property needed for the function, so that is not a good choice to make an api for example.
Algo wouldn`t it be happier to set this.alert to a function which receives a parameter?
It all depende on your needs...
I want to do the following in Javascript
function A(){
this.B = function() { ... };
this.C = function() { <<I need to call B() here>> } ;
};
I have read the following way of method overloading, but I want to know whether professional programmers would do it this way. I.e. if you would only do this as an exercise or experiment or would actually do this in production code.
function foo(a, b, opts) {
};
foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});
Just call B() from inside C();
function A(){
B = function() {
// Do something here
}
C = function() { B(); }
};
Or, if you just want to create an alias
function A(){
B = function() {
// Do something here
}
C = B
};
The clean way would be :
var A = function() { };
A.prototype.B = function() { };
A.prototype.C = function() { this.B(); };
The prototype is just a static set of properties that is cloned inside every new instance you create.
The difference between what you're doing and this is that in your case, methods are created and added when you are in the "constructor" of the object, while with this method they already are properties of the object before you enter its "constructor", and are only parsed once (when you add them to the prototype) instead of being parsed everytime you create a new instance, which is faster.
I think, correct me if i'm wrong.
var A = function() {
// this scope is what i mean by "constructor".
};
So I want to call function B in function A, but function B is fully declared after function A. I know that in c++ we'd use function prototypes on B, but what about javascript?
code:
markerArray = function() {
// some code here
this.array = [];
this.clearArray = function() {
for(var i = 0; i<this.getLength(); i++)
// for loop code
}
this.getLength = function() {
return this.array.length;
}
// some code here
}
these reason why I put this.getLength below is mainly because my coding style/structure is more readable this way
Javascript doesn't care about this requirement. It will simply work as long as Function A isn't called until after the file is loaded. Function A will be defined, Function B will be defined, then Function A can be called using Function B inside of it with no problem.
Not a problem. Function declarations are hoisted to the top of the enclosing variable environment, so they do not need to be declared in order.
A();
function A() {
B();
}
function B() {
alert('B was called');
}
If you meant something else, you'll need to explain it in your question.
It depends on how you declare your functions. If you declare a function via the Function constructor or a function expression, order matters.
a(1); //this call won't work
//function expression of an anonymous function assigned to the variable multiply
var a = function(i) {
b(i);
}
// b is defined using Function constructor
var b = new Function("i","alert('B was called with ' + i)");
a(1); //this call will work
My attempts at giving global scope to a nested JavaScript function are not working:
//DECLARE FUNCTION B IN GLOBAL SCOPE
function B;
function A() {
//DEFINE FUNCTION B INSIDE NEST
B() {
alert("function B is running");
}
}
//CALL FUNCTION B FROM GLOBAL SCOPE
B();
This is just curiosity -- you are correct that I don't really have any good reason to want to do this.
TIA -- I don't have an SO account to respond to your answers...
function B; will simply generate a syntax error.
You can use a function expression. As functions are first class objects, you can assign a function to a variable:
var B; // declare (global) variable (outer scope)
function A() {
// assign a function to it
B = function() {
alert("function B is running");
};
}
// we have to call A otherwise it won't work anyway
A();
// call B
B();
You could also let A return a function:
function A() {
return function() {
alert("function B is running");
};
}
B = A();
This would make the relation between A and B a bit clearer.
Of course you can always define a global variable by omitting var, but you should use this very carefully. Use as less global variables as possible.
function A() {
B = function() {
alert("function B is running");
};
}
And I bet there is a better way of doing it, depending on what your actual goal is.
More about Functions and function scope.
What about:
function A() {
window.B = function() {
alert("function B is running");
}
}
//CALL FUNCTION B FROM GLOBAL SCOPE
B();
You can do something like this:
function outer() {
function inner() {
// ..
}
window['inner'] = inner;
}
It's a little icky to have a direct reference to "window", so you could do this (from the global context):
(function (global) {
function inner() {
// code code code ...
}
global['inner'] = inner;
})(this);
There appear to be a couple of issues with your code
The first line doesn't appear to be legal Javascript (JSLint agrees). To declare an uninitialized variable use the var B; syntax
The code never calls A to initialize B so calling B() is invoking an uninitialized variable
I'm fairly certain the code to initialize B inside of A is also not legal.
Try the following
var B; // Establish B as a global scope variable
function A() {
B = function() {
alert('B is running');
};
}
A(); // Call the function which will cause B to be initialized
B(); // Run B
You're close, but not completely correct.
You have to define B as a variable and then assign a function to it.
Also run A() before executing B, otherwise B will be undefined. The easiest way of running it is the way that I show in my code example.
These are the smallest amount of changes to your code to make it work as you asked:
var B;
(function A() {
// define function B
B = function() {
alert("function B is running");
}
})();
// call function B globally
B();