There is a way (in angularJS) to pass by reference a variable in the scope in a function (to modify it)?
I've tried but the variable change doesn't happen.
Here my code
$scope.modifyVar = function (myVariable){
myVariable = 92;
}
$scope.modifyVar($scope.txtNumberOfChuck);
You cannot pass a variable by reference in Javascript. However you can pass the complete object and get your values changed.
In your case you can pass the $scope object and then modify the property value. Something like this:
$scope.modifyVar = function (myObj){
myObj.txtNumberOfChuck = 92;
}
$scope.modifyVar($scope);
Related
I would like to create a re-usable function that changes the boolean value of the variable that is passed in.
My example is below however this doesn't work as the first part of the statement 'item' is not assigned to the variable passed in.
let editable = true;
function toggleEditMode (item){
item = !item;
}
toggleEditMode(editable);
Any help?
You have to learn how js passes function arguments. It is passing by value here. Read this by value vs reference
Basically you can't pass by reference like you are trying to. You can make an object and then change a property on that object inside your function and it will work how you are expecting.
var i = { a:true }
function c(o){
o.a = !o.a
}
c(i)
console.log(i);
This may be very simple but i lost my way in finding the answer,
I have a named function inside a Backbone view. I'm trying to write unit test for this named function and i could see a variable is being declared in function scope. The state of this variable changes based on certain scenarios.
I have instantiated the view object inside my test suite and when i do a console.log(viewObject.namedFunction) i see the entire function being logged properly. Now how do i access the variable inside the namedFunction, i was expecting something like viewObject.namedFunction.variableName but it will not work and when i did that, it was not working as expected.
If the variable is tied to viewObject scope then it would have been easy to access it. But in this scenario it is not so can some one please help me in getting a hold on the variable inside named function in view object from test suite.
I think I understand your confusion, because when you define a variable using var in the window scope, it becomes a property on the window object... It would seem to follow that when you define a variable in a child scope, it should become a member of the local context, right? Nope. Globals are special ;-)
In fact, if that were the case, there would be no privacy!
If you want sign to be public, be explicit.
obj = {
namedFunction : function myself() {
console.log(myself);
myself.sign = 23;
}
};
obj.namedFunction.sign;
The only problem with this approach is that you can now assign a new value to sign from anywhere. The classic and preferred approach to this problem is to create a getter function for your private variable.
var obj = {
namedFunction : function myself() {
var sign = 3;
myself.getSign = function(){return sign;};
}
};
obj.namedFunction.getSign();
This isn't by any means the only approach, but I hope it was helpful.
One way to do this is like such:
namedFunction = (function(){
var theActualFunction = function(){
//Do something
//Access variable like: theActualFunction.MyVariable
};
theActualFunction.MyVariable = "value";
return theActualFunction;
}());
I have been watching a video series by Douglas Crockford. I am a little confused on the relationship of assigning variables as a parameter of assigning variables as a global variable, let me demonstrate.
var bob = 22; //global scope
function funky(parameter){
parameter = null; //sets the var passed in to null
bob = 44; //sets the bob
}
var hello = [];
funky(hello); // hello still has the value of an empty array even after the function is invoked.
bob; // value is 44
So 'var bob' is assigned 44 when funky() is invoked. This bob holds the new value outside the scope of the function.
var hello is passed as a parameter, while inside funky, it has the value null, outside when hello is invoked in global space, it holds the value of an empty array.
Is this just something I have to memorize? If a defined variable in global scope is passed as a parameter, it will only hold it's new assigned value within the scope of the function? Am I missing something at a broader scope with either how a parameter is passed and assigned in a function?
Here is a repl.it of the code with console.log outputs while inside and outside the function/global scope.
http://repl.it/NgN
Because this line
parameter = null;
Only sets the value of the function's parameter, not the value of the variable that was passed in. However, bob inside the function is interpretted as a reference to the global variable, so it does modify the external value.
Note, however, that objects are references, so if you wrote it like this:
function funky(parameter){
parameter.hello = null;
}
Then calling funky does directly modify the object that the parameter references.
var x = { hello: [] };
funky(x); // x => { hello: null }
Is this just something I have to memorize?
Yes, understanding how parameters are passed is pretty important.
If a defined variable in global scope is passed as a parameter, it will only hold it's new assigned value within the scope of the function?
Parameters only hold their values within the scope of the function. Global variables are, well, global, so if they are modified inside the function, they keep that value outside the function.
Also, be aware of hiding—if a parameter has the same name as a global variable, the parameter hides the variable within the scope of that function.
ok, so the following example will confuse you even more.
var a = {'a': 'A'};
function foo(param){param.a = 'B';}
foo(a);
// now print a
{'a': 'B'}
Here's an important concept:
Primitives are passed by value, Objects are passed by "copy of a reference".
As for more information, you can check this answer:
Does Javascript pass by reference?
Regarding this:
var hello is passed as a parameter, while inside funky, it has the value null, outside when hello is invoked in global space, it holds the value of an empty array.
Do not think of parameter as an alias for hello. They are distinct variables. They are free to point to different things. Assigning a value -- null in this case -- to parameter has no effect on hello. After that line, the global variable hello still points to an empty array. Only parameter points to null.
Furthermore, funky(hello) passes the value of hello to the funky function. Consider the following:
var arr = [];
function addElements(arr) {
arr.push(5);
arr.push(77);
}
The global arr is still empty after addElements executes. The arr inside the function is distinct from the arr in the global scope. (I should note that the contents of each arr may point to the same objects, but that's a separate issue.)
(Note also that some languages do allow the sort of aliasing you seem to expect, but that's not how parameters are passed in JavaScript.)
JavaScript assumes that if you assign a value to a variable it is in the global scope—unless that variable is declared with a var. Like for example, this:
var bob = 22; //global scope
function funky(parameter){
parameter = null; //sets the var passed in to null
var bob = 44; //sets the bob
}
var hello = [];
funky(hello); // hello still has the value of an empty array even after the function is invoked.
bob; // value is 22
Since the function's bob variable is declared with a var, it is owned by the local scope of the function and has no impact on the bob declared outside the function's scope.
Regarding how objects differ from primitives when passed into functions, check out Jonathan Snook's article http://snook.ca/archives/javascript/javascript_pass and the helpful comment from #p.s.w.g.
Blog.prototype.signature = "TEXT"
did this statement here created a signature variable?
because this statement didnt have var keyword in it.
Also additional question
why need to use function literals or function reference to make a function inside the prototype of an object?
ex. this wont work....
obj.prototype.toString{
return "dfasdfa";
}
did this statement here created a signature variable?
No, it set a property on the prototype of the Blog class.
why need to use function literals or function reference to make a function inside the prototype of an object?
Because you need to assign something to the property obj.prototype.toString. You have to set it to equal something (in this case, function), which you're not doing with the code snippet you displayed.
Example:
obj.prototype.toString = function() {
return "dfasdfa";
}
Note that you're actually assigning a value to that property with the = function bit. Then you go on to declare the function later on.
I have a variable that is the functions name. I want to be able to call on that function from the variable.
var CircuitBox= document.getElementById("QLCS")
var CircuitNumber = CircuitBox.selectedIndex;
var circuit = CircuitBox.options[CircuitNumber].value;
// This Variable takes on the functions name that id like to call
circuit;
Cheers!
In JavaScript object properties can be accessed via there name as a string by using bracket notation, eg:
var propertyVal = myObj["propertyName"];
And since globally scoped members are actually properties of the Global object, you can get the properties from the window object (which is a reference to the Global object). So, if your drop down list contains values that map to function names in the global scope, you can call that function like this:
window[circuit]();
I can think of two ways.
You can try window[circuit]() if it is a global function. The other option is to use eval, but eval is evil. So to avoid the evilness of eval, a better way might be to maintain a map of handlers:
var handlers = {
someValue: function() {
...
},
otherValue: function() {
...
}
};
In this map, you're associating someValue and otherValue with anonymous functions. So assuming that your select box contains the options someValue and otherValue, the appropriate function will be called based on what they select.
Then all you have to do is handlers[circuit]().