How do I pass variables by reference in JavaScript?
I have three variables that I want to perform several operations to, so I want to put them in a for loop and perform the operations to each one.
Pseudocode:
myArray = new Array(var1, var2, var3);
for (var x = 0; x < myArray.length; x++){
// Do stuff to the array
makePretty(myArray[x]);
}
// Now do stuff to the updated variables
What is the best way to do this?
There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:
function alterObject(obj) {
obj.foo = "goodbye";
}
var myObj = { foo: "hello world" };
alterObject(myObj);
alert(myObj.foo); // "goodbye" instead of "hello world"
You can iterate over the properties of an array with a numeric index and modify each cell of the array, if you want.
var arr = [1, 2, 3];
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i] + 1;
}
It's important to note that "pass-by-reference" is a very specific term. It does not mean simply that it's possible to pass a reference to a modifiable object. Instead, it means that it's possible to pass a simple variable in such a way as to allow a function to modify that value in the calling context. So:
function swap(a, b) {
var tmp = a;
a = b;
b = tmp; //assign tmp to b
}
var x = 1, y = 2;
swap(x, y);
alert("x is " + x + ", y is " + y); // "x is 1, y is 2"
In a language like C++, it's possible to do that because that language does (sort-of) have pass-by-reference.
edit — this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language — one that does involve objects — one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.
edit — here is a blog post on the topic. (Note the comment to that post that explains that C++ doesn't really have pass-by-reference. That is true. What C++ does have, however, is the ability to create references to plain variables, either explicitly at the point of function invocation to create a pointer, or implicitly when calling functions whose argument type signature calls for that to be done. Those are the key things JavaScript doesn't support.)
Primitive type variables like strings and numbers are always passed by value.
Arrays and Objects are passed by reference or by value based on these conditions:
if you are setting the value of an object or array it is Pass by Value.
object1 = { prop: "car" };
array1 = [1,2,3];
if you are changing a property value of an object or array then it is Pass by Reference.
object1.prop = "car";
array1[0] = 9;
Code
function passVar(obj1, obj2, num) {
obj1.prop = "laptop"; // will CHANGE original
obj2 = { prop: "computer" }; //will NOT affect original
num = num + 1; // will NOT affect original
}
var object1 = {
prop: "car"
};
var object2 = {
prop: "bike"
};
var number1 = 10;
passVar(object1, object2, number1);
console.log(object1); // output: Object { prop: "laptop" }
console.log(object2); // output: Object { prop: "bike" }
console.log(number1); // ouput: 10
Workaround to pass variable like by reference:
var a = 1;
inc = function(variableName) {
window[variableName] += 1;
};
inc('a');
alert(a); // 2
And yup, actually you can do it without access a global variable:
inc = (function () {
var variableName = 0;
var init = function () {
variableName += 1;
alert(variableName);
}
return init;
})();
inc();
Simple Object
function foo(x) {
// Function with other context
// Modify `x` property, increasing the value
x.value++;
}
// Initialize `ref` as object
var ref = {
// The `value` is inside `ref` variable object
// The initial value is `1`
value: 1
};
// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);
console.log(ref.value); // Prints "3"
Custom Object
Object rvar
/**
* Aux function to create by-references variables
*/
function rvar(name, value, context) {
// If `this` is a `rvar` instance
if (this instanceof rvar) {
// Inside `rvar` context...
// Internal object value
this.value = value;
// Object `name` property
Object.defineProperty(this, 'name', { value: name });
// Object `hasValue` property
Object.defineProperty(this, 'hasValue', {
get: function () {
// If the internal object value is not `undefined`
return this.value !== undefined;
}
});
// Copy value constructor for type-check
if ((value !== undefined) && (value !== null)) {
this.constructor = value.constructor;
}
// To String method
this.toString = function () {
// Convert the internal value to string
return this.value + '';
};
} else {
// Outside `rvar` context...
// Initialice `rvar` object
if (!rvar.refs) {
rvar.refs = {};
}
// Initialize context if it is not defined
if (!context) {
context = this;
}
// Store variable
rvar.refs[name] = new rvar(name, value, context);
// Define variable at context
Object.defineProperty(context, name, {
// Getter
get: function () { return rvar.refs[name]; },
// Setter
set: function (v) { rvar.refs[name].value = v; },
// Can be overrided?
configurable: true
});
// Return object reference
return context[name];
}
}
// Variable Declaration
// Declare `test_ref` variable
rvar('test_ref_1');
// Assign value `5`
test_ref_1 = 5;
// Or
test_ref_1.value = 5;
// Or declare and initialize with `5`:
rvar('test_ref_2', 5);
// ------------------------------
// Test Code
// Test Function
function Fn1(v) { v.value = 100; }
// Test
function test(fn) { console.log(fn.toString()); console.info(fn()); }
// Declare
rvar('test_ref_number');
// First assign
test_ref_number = 5;
test(() => test_ref_number.value === 5);
// Call function with reference
Fn1(test_ref_number);
test(() => test_ref_number.value === 100);
// Increase value
test_ref_number++;
test(() => test_ref_number.value === 101);
// Update value
test_ref_number = test_ref_number - 10;
test(() => test_ref_number.value === 91);
Yet another approach to pass any (local, primitive) variables by reference is by wrapping variable with closure "on the fly" by eval. This also works with "use strict". (Note: be aware that eval is not friendly to JavaScript optimizers, and also missing quotes around variable name may cause unpredictive results)
"use strict"
// Return text that will reference variable by name (by capturing that variable to closure)
function byRef(varName){
return "({get value(){return "+varName+";}, set value(v){"+varName+"=v;}})";
}
// Demo
// Assign argument by reference
function modifyArgument(argRef, multiplier){
argRef.value = argRef.value * multiplier;
}
(function(){
var x = 10;
alert("x before: " + x);
modifyArgument(eval(byRef("x")), 42);
alert("x after: " + x);
})()
Live sample: https://jsfiddle.net/t3k4403w/
There's actually a pretty sollution:
function updateArray(context, targetName, callback) {
context[targetName] = context[targetName].map(callback);
}
var myArray = ['a', 'b', 'c'];
updateArray(this, 'myArray', item => {return '_' + item});
console.log(myArray); //(3) ["_a", "_b", "_c"]
I personally dislike the "pass by reference" functionality offered by various programming languages. Perhaps that's because I am just discovering the concepts of functional programming, but I always get goosebumps when I see functions that cause side effects (like manipulating parameters passed by reference). I personally strongly embrace the "single responsibility" principle.
IMHO, a function should return just one result/value using the return keyword. Instead of modifying a parameter/argument, I would just return the modified parameter/argument value and leave any desired reassignments up to the calling code.
But sometimes (hopefully very rarely), it is necessary to return two or more result values from the same function. In that case, I would opt to include all those resulting values in a single structure or object. Again, processing any reassignments should be up to the calling code.
Example:
Suppose passing parameters would be supported by using a special keyword like 'ref' in the argument list. My code might look something like this:
//The Function
function doSomething(ref value) {
value = "Bar";
}
//The Calling Code
var value = "Foo";
doSomething(value);
console.log(value); //Bar
Instead, I would actually prefer to do something like this:
//The Function
function doSomething(value) {
value = "Bar";
return value;
}
//The Calling Code:
var value = "Foo";
value = doSomething(value); //Reassignment
console.log(value); //Bar
When I would need to write a function that returns multiple values, I would not use parameters passed by reference either. So I would avoid code like this:
//The Function
function doSomething(ref value) {
value = "Bar";
//Do other work
var otherValue = "Something else";
return otherValue;
}
//The Calling Code
var value = "Foo";
var otherValue = doSomething(value);
console.log(value); //Bar
console.log(otherValue); //Something else
Instead, I would actually prefer to return both new values inside an object, like this:
//The Function
function doSomething(value) {
value = "Bar";
//Do more work
var otherValue = "Something else";
return {
value: value,
otherValue: otherValue
};
}
//The Calling Code:
var value = "Foo";
var result = doSomething(value);
value = result.value; //Reassignment
console.log(value); //Bar
console.log(result.otherValue);
These code examples are quite simplified, but it roughly demonstrates how I personally would handle such stuff. It helps me to keep various responsibilities in the correct place.
Happy coding. :)
I've been playing around with syntax to do this sort of thing, but it requires some helpers that are a little unusual. It starts with not using 'var' at all, but a simple 'DECLARE' helper that creates a local variable and defines a scope for it via an anonymous callback. By controlling how variables are declared, we can choose to wrap them into objects so that they can always be passed by reference, essentially. This is similar to one of the Eduardo Cuomo's answer above, but the solution below does not require using strings as variable identifiers. Here's some minimal code to show the concept.
function Wrapper(val){
this.VAL = val;
}
Wrapper.prototype.toString = function(){
return this.VAL.toString();
}
function DECLARE(val, callback){
var valWrapped = new Wrapper(val);
callback(valWrapped);
}
function INC(ref){
if(ref && ref.hasOwnProperty('VAL')){
ref.VAL++;
}
else{
ref++;//or maybe throw here instead?
}
return ref;
}
DECLARE(5, function(five){ //consider this line the same as 'let five = 5'
console.log("five is now " + five);
INC(five); // increment
console.log("five is incremented to " + five);
});
Actually it is really easy. The problem is understanding that once passing classic arguments, you are scoped into another, read-only zone.
The solution is to pass the arguments using JavaScript's object-oriented design. It is the same as putting the arguments in a global/scoped variable, but better...
function action(){
/* Process this.arg, modification allowed */
}
action.arg = [["empty-array"], "some string", 0x100, "last argument"];
action();
You can also promise stuff up to enjoy the well-known chain:
Here is the whole thing, with promise-like structure
function action(){
/* Process this.arg, modification allowed */
this.arg = ["a", "b"];
}
action.setArg = function(){this.arg = arguments; return this;}
action.setArg(["empty-array"], "some string", 0x100, "last argument")()
Or better yet...
action.setArg(["empty-array"],"some string",0x100,"last argument").call()
JavaScript can modify array items inside a function (it is passed as a reference to the object/array).
function makeAllPretty(items) {
for (var x = 0; x < myArray.length; x++){
// Do stuff to the array
items[x] = makePretty(items[x]);
}
}
myArray = new Array(var1, var2, var3);
makeAllPretty(myArray);
Here's another example:
function inc(items) {
for (let i=0; i < items.length; i++) {
items[i]++;
}
}
let values = [1,2,3];
inc(values);
console.log(values);
// Prints [2,3,4]
Putting aside the pass-by-reference discussion, those still looking for a solution to the stated question could use:
const myArray = new Array(var1, var2, var3);
myArray.forEach(var => var = makePretty(var));
As we don't have javascript pass by reference functionality, the only way to do this is to make the function return the value and let the caller assign it:
So
"makePretty(myArray[x]);"
should be
"myArray[x] = makePretty(myArray[x]);"
This is in case you need assignment inside the function, if only mutation is necessary, then passing the object and mutating it should be enough
I know exactly what you mean. The same thing in Swift will be no problem. The bottom line is use let, not var.
The fact that primitives are passed by value, but the fact that the value of var i at the point of iteration is not copied into the anonymous function is quite surprising to say the least.
for (let i = 0; i < boxArray.length; i++) {
boxArray[i].onclick = function() { console.log(i) }; // Correctly prints the index
}
If you want to pass variables by reference, a better way to do that is by passing your arguments in an object and then start changing the value by using window:
window["varName"] = value;
Example:
// Variables with first values
var x = 1, b = 0, f = 15;
function asByReference (
argumentHasVars = {}, // Passing variables in object
newValues = []) // Pass new values in array
{
let VarsNames = [];
// Getting variables names one by one
for(let name in argumentHasVars)
VarsNames.push(name);
// Accessing variables by using window one by one
for(let i = 0; i < VarsNames.length; i += 1)
window[VarsNames[i]] = newValues[i]; // Set new value
}
console.log(x, b, f); // Output with first values
asByReference({x, b, f}, [5, 5, 5]); // Passing as by reference
console.log(x, b, f); // Output after changing values
I like to solve the lack of by reference in JavaScript like this example shows.
The essence of this is that you don't try to create a by reference. You instead use the return functionality and make it able to return multiple values. So there isn't any need to insert your values in arrays or objects.
var x = "First";
var y = "Second";
var z = "Third";
log('Before call:',x,y,z);
with (myFunc(x, y, z)) {x = a; y = b; z = c;} // <-- Way to call it
log('After call :',x,y,z);
function myFunc(a, b, c) {
a = "Changed first parameter";
b = "Changed second parameter";
c = "Changed third parameter";
return {a:a, b:b, c:c}; // <-- Return multiple values
}
function log(txt,p1,p2,p3) {
document.getElementById('msg').innerHTML += txt + '<br>' + p1 + '<br>' + p2 + '<br>' + p3 + '<br><br>'
}
<div id='msg'></div>
Using Destructuring here is an example where I have 3 variables, and on each I do the multiple operations:
If value is less than 0 then change to 0,
If greater than 255 then change to 1,
Otherwise dived the number by 255 to convert from a range of 0-255 to a range of 0-1.
let a = 52.4, b = -25.1, c = 534.5;
[a, b, c] = [a, b, c].map(n => n < 0 ? 0 : n > 255 ? 1 : n / 255);
console.log(a, b, c); // 0.20549019607843136 0 1
I have a text string that is correctly formatted as a function and I would like to convert it to an actual function. The text string looks like:
function object_123(){
object_123_Action();
my_clicked(obj);
}
Apart from the word "function" and {}; all other text is dynamically constructed. i.e. It may never contain object_123_Action(), however, it will be something similar, basic function calls. The only issue will be the obj will need to be the object that the function is assigned to.
Basically, I need:
this.func = eval(func_txt); //to actually work.
Where func_txt is:
function object_123(){
object_123_Action();
my_clicked(this);
}
Your string contains a function declaration.
When evaluated, it creates a object_123 variable in the scope of eval (which you can then call later) and returns nothing.
If you want to assign the function to this.func then you need to convert the declaration into a function expression. You can do that by wrapping it in parens.
this.func = eval("(" + func_txt ")" );
var func_txt = "function object_123(){\
object_123_Action();\
my_clicked(obj);\
}";
this.func = eval("(" + func_txt + ")");
var obj = "...";
function object_123_Action() {
alert(1);
}
function my_clicked() {
alert(2);
}
this.func();
You can store your functions in an array on the object.
Then, loop though the functions in another function and execute them.
var myObj = { 'myfunctions': [ ] };
and to add functions:
myObj.myFunctions.push (function () { /*function code here*/ });
Or if you already have a named function:
myObj.myFunctions.push (nameOfFunction);
And to call all the functions, use this function (don't add this function to myObj)
function executeMyFunctions (myObj) {
for (var i = 0; i < myObj.myFunctions.length; i++) {
myObj.myFunctions[i]();
}
}
And if it's possible to avoid using eval, you should.
Try this:
function parseStringToFunction(func) {
func = func || '(function(){return null;})';
return (new Function('return ' + func)());
};
var stringifyFunction = '(function(a, b) { return a+b; })';
var callStringifyFunction = parseStringToFunction(stringifyFunction)(1, 2);
alert(callStringifyFunction); // results is 3
Also read this out: detail about eval() and new Function()
Try this-
$("<script type='text/javascript'></script>").html(func_txt).insertAfter($("script"));
This works:
assert( eval("(function(a, b) { return a+b; })")(1, 2) == 3 )
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#eval_as_a_string_defining_function_requires_(and)_as_prefix_and_suffix
Simply wrap the function in parens.
it is possible to set value for the local variable when you call it ? it is my code
var myvar={
F:function(){
var x;
return x;}
}
my problem is when I call the x variable and set value like myvar.F().x="hello"; . then recall it console.log(myvar.F().x) x don't contain that value only return undefined ? how i can fix it but please don't suggest me to set the value inside F function AND Using Parameters from F function ! other way because I want make a dynamic variable not static value Thanks for help
Despite the answers here, some comments are very clear. The thing you want is not possible.
You can set a variable to the return of a function, but I won't be saved anywhere. The reference is immediately lost.
var myvar = {
f: function() {
var x = 'something';
return x;
}
}
document.write(myvar.f());
This will return x from the method f inside the object myvar. The object returned is a string. In your original code x isn't event defined as something. Since everything in JavaScript is an object, you can assign a property x to the result if it's defined, BUT that is not the case here:
var myvar = {
f: function() {
var x;
return x;
}
}
var a = myvar.f();
document.write(a + "<br />");
document.write(Object.prototype.toString.call(a) + "<br />"); //returns [object Undefined]
So you're attaching a property to a undefined which never gets set. To be able to set x you need to make it a property of the function myvar. Setting it to the method will only work if you don't invoke the method. Invoking the method causes it to return the variable that is not bound to the method object itself.
If I understand correctly, you want the result of the function call to be a stateful object that you can set and fetch values from.
I'm also assuming you don't want the object which is returned from the function to be accessible anywhere else in the parent object.
In order to do this, you'll need to change the way your object is created.
var Factory = function () {
var _priv = {
x: "something"
};
return {
F: function () {
return _priv;
}
};
};
var myvar = new Factory();
myvar.F().x; // "something"
myvar.F().x = "hello world"; // "hello world"
So, the creation of the initial object is a bit different, but you have the desired results.
If you don't mind that the returned objects properties are accessible elsewhere on the parent object, you could do this:
var myvar = {
_priv: {
x: "something"
},
F: function () {
return this._priv;
}
};
myvar.F().x; // "something"
myvar.F().x = "hello world"; // "hello world"
The downside being that the _priv property is also accessible on the main object:
myvar._priv.x; // "hello world"
Does this answer your question?
var myvar = {
F: function(x) {
if (x) {
this.x = x; // if you are setting the value of x
}
else {
return this.x; // if you want the value of x
}
}
}
myvar.F("foo"); // Setter
myvar.F(); // "foo" (Getter)
(You'll need to open up the console on your browser) does this help to mimic the behavior you want? I'm not 100% on why you would want to do something like this to begin with.
var myvar = {
f: function() {
this.x = this.x ||'';
return this;
}
}
console.log(myvar.f());
myvar.f() .x = "Not something";
console.log(myvar.f.x);
console.log(myvar.f().x);
Methods(Object's function) can refer to object's variable using the "this" keyword.
Can function's properties refer to function variables?
Eg:-
function foo()
{
var x=5;
}
foo.help = {o1:x};// o1 is not initialized to x.
//Using o1:this.x also doesn't help. Why? Explain please.
Is there anyway to initialize o1 to x?
Example 9-1. A simple JavaScript class
// range.js: A class representing a range of values.
// This is a factory function that returns a new range object.
function range(from, to) {
// Use the inherit() function to create an object that inherits from the
// prototype object defined below. The prototype object is stored as
// a property of this function, and defines the shared methods (behavior)
// for all range objects.
var r = inherit(range.methods);
// Store the start and end points (state) of this new range object.
// These are noninherited properties that are unique to this object.
r.from = from;
r.to = to;
// Finally return the new object
return r;
}
// This prototype object defines methods inherited by all range objects.
range.methods = {
// Return true if x is in the range, false otherwise
// This method works for textual and Date ranges as well as numeric.
includes: function(x) { return this.from <= x && x <= this.to; },
// Invoke f once for each integer in the range.
// This method works only for numeric ranges.
foreach: function(f) {
for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
},
// Return a string representation of the range
toString: function() { return "(" + this.from + "..." + this.to + ")"; }
};
// Here are example uses of a range object.
var r = range(1,3); // Create a range object
r.includes(2); // => true: 2 is in the range
r.foreach(console.log); // Prints 1 2 3
console.log(r); // Prints (1...3)
What I understand :
Range is a function with variable from and to.
Range.methods is Range's property.It is defined outside Range() but it can still access from and to (using this.from and this.to ). How?
Thank you.
EDIT
this answer is based on edited question -- original answer is below
Your understanding is a little backwards.
The function doesn't have from and to in the way you think it does.
If I built this a different way, to get almost all of the same functionality, but be much, much easier for a person who is new to JS to understand, I would write it like this:
// my `makeRange` function makes an object
// then it gives it all of the things a range object needs
// then it returns the new object
var makeRange = function (min, max) {
// there are cleaner more-compact ways of doing this
// I'm writing this out in long-form to show you exactly what's going on
var rangeObject = {};
rangeObject.from = min;
rangeObject.to = max;
rangeObject.includes = includes;
rangeObject.foreach = foreach;
rangeObject.toString = toString;
return rangeObject;
};
// these are all of the functions inside of `range.methods`
// they don't have to be attached to the function ***AT ALL***, for ***ANY REASON***
// other than the author wanted them to be there for the sake of organization
// Here, I'm just putting them out on their own, for sake of clarity
var includes = function (x) { return this.from <= x && x <= this.to; },
foreach = function (func) {
var min = this.from,
max = this.to,
i = 0;
for (i = min; i <= max; i += 1) { func(i); }
},
toString = function () { return "(" + this.from + "..." + this.to + ")"; };
var range_3_to_5 = makeRange(3, 5),
range_6_to_12 = makeRange(6, 12);
range_3_to_5.from; // 3
range_6_to_12.includes(8); // true
range_6_to_12.foreach(function (i) { console.log(i); }); // [logs:] 6,7,8,9,10,11,12
The methods on range in the example aren't a part of the function.
They're methods which are given to the objects, as they are constructed.
In the example you gave, this is happening inside of the r = inherit(range.methods); call, which isn't explained in that block of code.
The this doesn't refer to the function at all.
It refers to the final object which uses the methods, at the time the method is called.
My range_3_to_5 and range_6_to_12 are both using the same copy of includes.
When range_3_to_5.includes(6); is called, this is set to range_3_to_5, and then the function uses this.from and this.to to determine if x is in the range.
There's no complex magic here.
We're just calling a function which "makes" something in a specific way, like a factory assembly-line, and then passes the finished version out.
It's attaching shared functions to each copy on the assembly line, and those shared functions use this to figure out which copy they're dealing with at the time.
var car = { license : "a32 vx98" },
truck = { license : "vdx 2000" },
jeep = { license : "mkv 3a2b" };
var read_license = function () { console.log(this.license); };
car.read_license = read_license;
truck.read_license = read_license;
car.read_license(); // [logs:] a32 vx98
truck.read_license(); // [logs:] vdx 2000
I can even call the function on its own, using the function's .call or .apply method to manually set this.
read_license.call(jeep); // [logs:] mkv 3a2b
Or use .bind to save a version of the function which ALWAYS uses the same value for this.
var read_car_license = read_license.bind(car);
read_car_license(); // a32 vx98
previous answer below
Not even remotely.
Variables live inside of the functions that they're created in:
var myFunction = function () {
var myValue = 23;
console.log(myValue);
};
myFunction(); // [log:] 23
console.log(myValue); // undefined
Values can live inside of functions further in:
var myFunction = function () {
var myValue = 23,
sayValue = function () {
console.log(myValue);
};
sayValue(); // will log 23 when you call `myFunction`
}
myFunction(); // [log:] 23
But if you want your variable to live OUTSIDE of the function (instead of further inside), then you either need to return the value to something, or set it to something, directly, from inside of the function.
var myOutsideValue = 42,
myFunction = function () {
var myValue = 23;
myOutsideValue = myValue;
};
console.log(myOutsideValue); // 42
myFunction();
console.log(myOutsideValue); // 23
Or returned...
var myReturnedValue = 0,
myFunction = function () {
var myValue = 23;
return myValue;
};
myReturnedValue = myFunction();
console.log(myReturnedValue); // [log:] 23
Or you can pass in an array or object to modify:
var myObject = {},
myFunction = function (obj) {
var myValue = 23;
obj.value = myValue;
};
myFunction(myObject);
console.log(myObject.value); // [log:] 23
Functions CAN reference themselves.
And because in JavaScript, functions are objects (and can have their own properties and methods), you can add things to them the same way you'd add properties to any {} object.
var myFunc = function () {
var myValue = 23;
myFunc.properties = {};
myFunc.properties.value = myValue;
};
myFunc();
console.log(myFunc.properties.value); // [logs:] 23
None of this has anything to do with this.
this is used for the opposite of what you're looking for.
It's for when you're inside a function which is attached to an object, and you want to read other properties/run other methods that are on that object.
var myObject = {
x : 23,
y : 42,
sayX : function () { console.log(this.x); },
sayY : function () { console.log(this.y); }
};
myObject.sayX(); // [logs:] 23
this is used in a couple of other spots, but really, that's it's primary role: accessing or setting values/methods on the object which the function is attached to (either through dot-property access obj.func(), or through manual setting, using .call/.apply/.bind), with the other very regular situation being the creation of new objects, using the new keyword.
So the way to get your x to work isn't to figure out this, it's to set it within the function, itself, or, more-appropriately, pass x out (return x) to another variable, outside, and then set the value yourself.
var foo = function () {
var x = "x";
return x;
},
variable; // === undefined
foo.help = { o1 : 0 };
variable = foo(); // variable === "x"
foo.help.o1 = variable;
// or shorter: foo.help.o1 = foo();
Alternative:
var help = { o1 : 0 },
foo = function (obj) {
var x = "x";
obj.o1 = x;
};
foo(help);
foo.help = help;
this only works inside of functions
var obj = {};
obj.x = 12;
obj.y = this.x + 5; // DOESN'T WORK
If this works in the last example, it's only because it's using this from inside of a function which would be referring to the FUNCTION'S this, and not to obj. And if you're calling a function which isn't attached to an object (obj.func(); or func.call(obj) or new_func = func.bind(obj);), then this will point to window.
In the context foo.help = {o1: x}, you are not in the same lexical scope as the definition of x, which would be inside of the foo function scope. This also applies to this.x (which apply in object scope).
function foo() {
var x = 5;
this.help = x;
}
i'm creating a game in javascript for college and i have a button to call a function but i need it to include variables from another function
if i put the function inside the other function where the variables are the button doesn't call it
is there a way of doing this or to get the variables that were created in the first function and use them in the second function
it is a simple maths game where you get a random number a random sum and another random number
(i.e. 5+7, 4*3, 2/6, etc,)
so i've got a function to show the random number using
var ranNum1a=Math.floor(Math.random()*10);
i need the other function to check the users answer but i need to know what the random number was from the other function
You would need to make those variables global
example:
var myValue;
function setValue()
{
myValue = "test";
}
function getValue()
{
alert(window.myValue); // yup, it's "test"
}
source..
For simplest case, passing variables to another function might be the best approach to this problem.
Here is an illustration:
function f1(var1, var2) {
//do you stuff then pass the variable to another function
f2(var1, var2);
}
function f2(v1, v2) {
// here v1 will get the value from var1 and v2 from var2 if passed from within the function f1
}
var ranNum1a;
function show() {
ranNum1a = Math.floor(Math.random()*10);
// show it
}
function check() {
if (ranNum1a == 42) {
alert("Ok");
}
}
I found this to be extremely helpful in relation to the original question:
Return the value you wish to use in functionOne, then call functionOne within functionTwo and place the result into a fresh var. This should enable you to use the var declared in functionOne, within functionTwo.
function functionOne() {
var variableThree = 3;
return variableThree;
}
function functionTwo() {
var variableOne = 1;
var var3 = functionOne();
var result = var3 - variableOne;
console.log(variableOne);
console.log(var3);
console.log('functional result: ' + result);
}
functionTwo();
function function1() {
var a = 1;
localStorage.setItem("var1", a);
alert("Function1 value of a: " + a);
}
function function2() {
var a = localStorage.getItem("var1");
alert("Function2 value of a: " + a);
}
<!-- first declare the variable -->
<script>
var x;
function something(){
var x = document.getElementById('hello').innerHTML
}
function other(){
document.write(x);
`you can use x here x is same as document.getElementById('hello').innerHTML`
}
</script>