This question already has answers here:
Does JavaScript pass by reference? [duplicate]
(13 answers)
Closed 6 years ago.
Im working on a project, and in an attempt to shorten the amount of code I wrote a function to call all of them at once. It looks something like this function Function(peram1) {peram1 = peram1 += 5}; And I call it like so Function(someVariable) My issue is that I need to change the variable someVariable from inside the function, even though the value of peram1 is simply just the value of someVariable, but cant directly change it. I call multiple of these functions, so I cant simply just call the actual variable name from within.
var someVariable = 5;
var someSeperateVariable = 8;
function Function(peram1) {
peram1 = peram1 += 5;
};
Function(someVariable);
Function(someSeperateVariable);
console.log(someVariable, someSeperateVariable);
You can use an object to store variables, pass property name and object to function
var obj = {someVariable:5, someSeparateVariable:8};
function fn(prop, obj) {
obj[prop] += 5;
};
fn("someVariable", obj);
fn("someSeparateVariable", obj);
console.log(obj.someVariable, obj.someSeparateVariable);
Consider returning a value from Function
var peram1 = Function(Peram1);
Another option in case peram1 is not an object - is to wrap peram1 with an object:
var objContainPeram1 = { peram1: peram1 }
Function (objContainPeram1) {
objContainPeram1.peram1 = objContainPeram1.peram1 + 5
}
Another solution would be to wrap your code in a function to create a closure:
function closure() {
var someVariable = 5;
var someSeperateVariable = 8;
function foo() {
someVariable += 5;
};
console.log(someVariable)
foo()
console.log(someVariable)
}
closure()
Related
This question already has answers here:
How do I pass variables between functions in Javascript?
(3 answers)
Closed 6 months ago.
I am learning Javascript. I want to pass variable from one function to another. I am trying to catch option in funTwo but I do not want to declare the variable as global or use var.
function funOne(one) {
let tags = '<div class= "options">' + arr[1] + '</div>';
const option = options_list.querySelectorAll(".options")
}
function funTwo(two) {
option.classList.add("correct")
}
In javascript, variables declared with const or let are scoped: this means they exist and are accessible only in the current scope.
When you declare a variable inside a function, it is inside the function scope and inaccessible from anything that is not in that scope, including other functions. If you want to use this variable, you need to pass it either as parameter or returning it from a function call.
function b(value) {
console.log(value);
}
function a() {
const foo = 1;
b(foo);
}
or
function b() {
let value = a();
console.log(value);
}
function a() {
return 1;
}
Yes, you can return option from funOne and get it in funTwo.
function funOne(one){
let tags = '<div class = "options">' + arr[1] + '</div>'
const option = options_list.querySelectorAll(".options")
return option
}
function funTwo(two){
const option = funOne() // the function will return option.
option.classList.add("correct")
}
This question already has an answer here:
Why can’t I assign values to a variable inside a named function expression with the same name?
(1 answer)
Closed 3 years ago.
var functionVariable = function functionExpressionName() {
functionExpressionName = 1;
console.log(functionExpressionName) // function
};
functionVariable();
If You run this example you can see we can not reassign to functionExpressionName anything.
But this is also interesting we can reddeclare functionExpressionName and after this we can assign anything to functionExpressionName
var functionVariable = function functionExpressionName() {
function functionExpressionName() {
}
functionExpressionName = 1;
console.log(functionExpressionName); // 1
};
functionVariable();
If you enable strict mode, the error becomes a bit clearer:
'use strict';
var functionVariable = function functionExpressionName() {
functionExpressionName = 1;
console.log(functionExpressionName) // function
};
functionVariable();
Uncaught TypeError: Assignment to constant variable
The function name is un-reassignable inside the function, but you can create a new variable with the same name inside the function body. One way of looking at it is that the function name is declared with const just outside the function body:
var functionVariable = (() => {
const functionExpressionName = function () {
functionExpressionName = 1; // Clearly wrong - functionExpressionName is a const
// but it would work if you declared a *new* variable,
// which has a different lexical binding
console.log(functionExpressionName) // function
};
return functionExpressionName;
})();
functionVariable();
This isn't exactly what happens, but it's pretty close.
This question already has answers here:
dynamically call local function in javascript
(5 answers)
Closed 8 years ago.
I'm having a difficulty calling a function inside of another function when its name is in a variable:
var obj = {}
obj.f = function() {
var inner = {
a: function() {
function b() {
alert('got it!');
}
b(); // WORKS AS EXPECTED
x = 'b';
[x](); // DOESN'T WORK, NEITHER this[x]() window[x](), etc.
}
}
inner.a();
}
obj.f();
I tried prefixing [x]() with different scope paths but so far w/o success. Searching existing answers did not turn up anything. It works with this[x]() if b() is placed directly inside object inner. I would like to keep b() as a function inside function a() because of variable scope in function a(), otherwise I would need to pass many parameters to b().
////
Re duplicate question: Quentin provided a more elegant answer in this thread imo.
There is no sensible way of accessing an arbitrary variable using a string matching the name of the variable. (For a very poor way to do so, see eval).
[x](); // DOESN'T WORK
You're trying to call an array as a function
NEITHER this[x]()
The function isn't a property of the inner object.
window[x](), etc.
Since it isn't a global, it isn't a property of the window object either.
If you need to call a function based on the value of a string variable, then organise your functions in an object and access them from that.
function b() {
alert('got it!');
}
var myFunctions = {
b: b
};
x = 'b';
myFunctions[x]();
Try this. Currently you are assigning string to variable x, instead of a function variable.
x = b;
x();
The problem is with your assignment
use x = b instead of x = 'b' to assign the function object as the latter just assigns the string into x.
Once you fix your assignment you can invoke the function as
x();
a.x();
a[x]();
etc.
You should make array for the function and then access using name in your variable as follow:
var obj = {}
obj.f = function() {
var inner = {
a: function() {
// set up the possible functions:
var myFuncs = {
b: function b() {alert('got it!');}
};
//b(); // WORKS AS EXPECTED --> commented this code
x = 'b';
myFuncs[x]();
}
}
inner.a();
}
The function declaration b will be captured in the closure of the anonymous function expression assigned as a.
When var is used in a closure, there is no (available in JavaScript) Object which gets assigned a property similar to what happens with window in the Global Scope.
Writing a function declaration effectively vars the name of the function.
If you really want to access a variable (i.e. b) by String, you will either need to create an Object which holds b similar to what you've done for a, or (and possibly dangerously) rely on an eval to convert "b" to b.
If you can't create the whole Object ahead-of-time, you can use this format
/* in (higher?) scope */
var fnRef = {};
// now when you
function b() {/* define as desired */}
// also keep a ref.
fnRef['b'] = b;
// fnRef['b']() will work **after this line**
let's say your code is like this:
//instead of x = 'b'
x = function(){}
then your solution could be like this:
var obj = {}
obj.f = function() {
var inner = {
a: function() {
function b() {
alert('got it!');
}
b(); // WORKS AS EXPECTED
//you can define it as a variable
var x = function(){};
//and call it like this
x();
//or define it like this
this[x] = function(){};
//and call it like this
this[x]();
//but you are creating an array [x] which is not a function
//and you are trying to call an array????
[x](); // DOESN'T WORK, NEITHER this[x]() window[x](), etc.
}
}
inner.a();
}
obj.f();
I just write a test html file to learn about object in javascript. The code is as follows
in script tag
<script type="text/javascript">
var obj = new ParentFn();
var obj2 = new AnotherParentFn();
var temp;
function initer()
{
temp = obj.Adding();
obj2.caller();
}
function ParentFn()
{
this.a = 10;
this.b = 20;
}
function AnotherParentFn()
{
this.a = 30;
this.b = 50;
}
AnotherParentFn.prototype.caller = function()
{
var self = this;
temp();
}
ParentFn.prototype.Adding = function()
{
var self = this;
document.getElementById("id_div1").innerHTML = " Method Called and Result of a+b is " + (self.a + self.b);
}
</script>
In body i use
<button onclick="initer()"> Click here to test </button>
<div id="id_div1"></div>
Problem is when AnotherParentFn.prototype.caller is called from initer() function temp variable is still undefined. What is wrong with the code??
My task is to assign the function ParentFn.prototype.Adding in a global variable and call the global variable from AnotherParentFn.prototype.caller function. How to achieve it?
You don't need to save it as a global variable. It's already saved in ParentFn.prototype. All you need to do is invoke it with .call and pass in your desired receiver. You can implement AnotherParentFn.prototype.caller like this:
AnotherParentFn.prototype.caller = function()
{
ParentFn.prototype.Adding.call(this);
}
This way you can get rid of temp completely. You also don't need to assign this to a local var self everywhere.
Parentheses are used to execute a function.
When you assign the value to temp, you are calling the function and assigning the result (undefined) to temp. To store a reference to the function in temp, omit the parentheses.
temp = obj.Adding;
By writing temp = obj.Adding(); it stores the return value. not function pointer in temp. Use this
function initer()
{
temp = obj.Adding;
obj2.caller();
}
First of all, the reference to obj.Adding is not assigned properly; it should be this (without parentheses):
function initer()
{
temp = obj.Adding;
obj2.caller();
}
Then, inside AnotherParentFn.prototype.caller itself, you must pass the current object as this explicitly during the invocation by using .call():
AnotherParentFn.prototype.caller = function()
{
temp.call(this);
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Return Global Variable from Javascript Method
I have this.
var thisData = "";
function calculateThings(newData) {
thisData = newData.things.otherthings //has a value of 10;
}
alert(thisData) //returns nothing
What am I doing wrong?
you need to call your function:
calculateThings(newData);
should be more like:
var thisData = "";
function calculateThings(data) {
thisData = data.things.otherthings //has a value of 10;
}
calculateThings(newData);
alert(thisData) //returns nothing
where data is your parameter, and you can pass whatever you want into it.
You created a function but never call it. You need to call it via:
var thisData = "";
function calculateThings(newData) {
thisData = newData.things.otherthings //has a value of 10;
}
alert(calculateThings(thisData));
or you can self-invoke the function like:
(function calculateThings(newData) {
thisData = newData.things.otherthings //has a value of 10;
})()