How can i pass an attribute to a javascript function by reference? - javascript

I want to manipulate some attributes of my page elements in a java script function , take a look at this example and maybe you find a solution to do this.
function doubleup(attr){
attr*=2;
}
doubleup(myDIV.style.zIndex);
doubleup(myDIV.style.opacity);

In short, you don't. You can't pass primitive values by reference.
You can do that with non-primitive values, though, as they're always passed as reference. Example:
function doubleup(object, property) {
object[propety] *= 2;
}
doubleup(myDiv.style, "zIndex");
doubleup(myDiv.style, "opacity");
Primitive data types are strings, numbers, booleans and, recently, Symbols

You only pass the value of this attribute to the function, so you don't change the style element, you only change the value, can do it in this way:
function doubleup(attr){
return attr*=2;
}
myDIV.style.opacity = doubleup(myDIV.style.opacity);
myDIV.style.zIndex = doubleup(myDIV.style.zIndex);
By the way, you have to use zIndex instead of z-index to manipulate this value.
Another possible solution is:
function doubleup(el){
el.style.opacity*=2;
}
function doubleupZIndex(el){
el.style.zIndex*=2;
}
doubleupOpacity(myDIV);
doubleupZIndex(myDIV);

Related

Javascript: Checking equality of the functions themselves, not return values

I want to pass a function into another as a property. I then want to test whether that function is equal to a particular function:
function f(func) {
if (func === testFunc) {
console.log("They're the same!")
}
}
function testFunc(x) {
return x+1
}
f(testFunc)
The above works as expected. The conditional in the top function passes and the line is outputted to the console. However, if I pass the function with a property of its own, it is found not to be equal:
f(testFunc(2))
I assume this is because the return value is different. So how do I test whether the actual functions are the same, not their returning values? Is there a way?
If you want to check, if 2 object's content are the same, then you need to use the uneval function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval
Keep in mind this is worse than eval, so try to avoid it if possible.

Use a variable in function argument

What I am trying to do is set a variable specified in a function to something, see below if that doesn't really make sense.
function getRandomFromArray(arrayName,storeVariable)
{
storeVariable = arrayName[Math.floor(Math.random() * arrayName.length)]
}
var petTypeArray = ['Cat','Dog','Ferret','Spider','Companion Bot'];
getRandomFromArray(petTypeArray,petType)
For example, set petType to a random string in petTypeArray. Am I doing it right? Am I able to do it like this?
You could use the return value of the function:
function getRandomFromArray(arrayName) {
return Math.floor(Math.random() * arrayName.length);
}
var petTypeArray = ['Cat', 'Dog', 'Ferret', 'Spider', 'Companion Bot'];
var randomElement = getRandomFromArray(petTypeArray);
This makes the code more readable. Modifying parameter values inside the function is possible but it doesn't work with primitive types such as strings and integers. You can only modify the properties of some complex object.
No. You are not doing in correctly. The reason is, the variables are just references to data. They don't mean anything themselves. So, when you say
storeVariable = Math.floor(Math.random() * arrayName.length)
you are making storeVariable refer to a new value. Thats it. You are not making changes to storeVariable. That is why it will not work. Instead, you can return the value from the function like this
function getRandomFromArray(arrayName)
{
return arrayName[Math.floor(Math.random() * arrayName.length)];
}
and make some other variable refer the returned data, like this
var randomData = getRandomFromArray(myArray);
In JavaScript, all parameters are passed by value.
This means that storeVariable receives a COPY of the value that you call with. That local copy can change but it can't influence the original.
(Yes, ALL parameters are passed by value. For those about to downvote me, objects are passed by value. That value just happens to be a reference to the original object.)

Change array through a function parameter

I need to change array to a new array created inside a function.
function changeArr(a)
{
a=["hello"]; // don't work
//a.push("hello"); //works, but the real array pretty big (dont want copy)
}
var arr=[];
changeArr(arr);
console.log(arr); // should echo ["hello"]
It seems like all you really want to do is clear the array that is passed into the function, before appending to it:
function changeArr(a)
{
a.length = 0; // clear the array here if you don't care about the prev. contents
a.push("hello"); // this adds to the array that was passed in
}
Inside the function changeArr(), a is only a local variable referencing the array you passed as an argument when calling this function. a=["hello"] makes this local variable reference a newly created and different array. This changes does not affect the original array passed in. What you want to do is likely what Miky Dinescu suggested: use the local variable to modify the original array but don't assign/attach anything new to it.
If you are trying to completely replace the array, you can use a return value.
function changeArr()
{
return ["hello"];
}
arr = changeArr();
If there is a reason you aren't doing this, explain and I'll adjust my answer.
You can use the splice method as such:
a.splice(0,a.length,"hello")

JavaScript passing argument via reference

let say I've got this kind of code:
var obj1 = {test: false};
function testCondition(condition){
if (!condition){
testCondition(condition);
}
}
testCondition(obj1.test);
above code will pass false as argument to testCondition. How can I do to pass reference to obj1.test instead of passing it's value?
EDIT
wow, thanks for quick responses!! :) But I would like to add, that I cannot pass the whole object, because I would like to build one generic function/method which would just check parameter and do onComplete callback or onError callback. Above code is only example of situation where I am right now.
You have two choices, from what I can see:
Pass the object itself, instead of its member. You can then access and modify the member:
function testCondition(object) {
if (!object.test) {
testCondition(object);
}
}
testCondition(obj1)
Alternatively, since you're changing a single value, you can have that value be returned by the function:
function testCondition(condition) {
if (!condition){
return testCondition(condition);
}
}
obj1.test = testCondition(obj1.test);
FYI, your code as you've displayed it right now will cause an infinite recursion if condition is false.
What's wrong with return values?
Alternatively you can wrap the argument in an object:
function foo(arg) {
var val = arg.val;
// do something with val
arg.val = val;
}
var arg = {val:"bar"};
foo(arg);
// do something with arg.val
You can't.
Pass obj1 instead, then examine condition.test inside the function.
You can't. JavaScript passes objects and arrays by reference, primitives (integers, strings, booleans) by value. What you're asking for is impossible, except by bad work-arounds:
function ugly(result) {
result.success = true;
}
var result = {};
ugly(result);
Instead, just return your value. It's how JavaScript is meant to work.
pass the whole object instead of its property:
testCondition(obj1);
and then
if(!passedObj.test){
etc...

Is it possible to use a variable to call an object who's name is the same as the variables value?

Let's say I have a function which is being passed a string which originally came from getElementById, and I have an object with the same name as that string's value, is there a way to call that object? I won't know which object I want until I get that value from the element's ID.
For Instance:
StartingFunction(SomeID){
someVariable = document.getElementById(SomeID).id
somefuntion(someVariable)
}
someFunction(ElementID){
// need to call Object.Value of whichever object is named the same as the value of
//ElementID here
}
ElementID.Value obviously won't work since ElementID is just a variable, not an object...
You can pass the element directly to someFunction.
For example:
StartingFunction(SomeID){
var element = document.getElementById(SomeID);
somefuntion(element);
}
someFunction(element){
alert(element.id);
alert(element.value);
// Any other processing you want to do with element
}
Or if you need to be able to get an element from an id just use getElementById
someFunction(id) {
var element = document.getElementById(id);
alert(element.value);
// Any other processing you need to do with the element DOM object
}
What you call ElementID is actually the element itself because you are passing document.getElementById() into somefunction.
if function is in global scope you can just window[ElementID]
for example:
someFunction(ElementID){
return window[ElementID].value;
}
Don't do that. This is bad design and will lead to enormous pain and hard-to-find bugs down the road.
Instead, use a global object that has all of the objects you want to reference.
var valueMap = new Object();
function setValue(id, valueObject) {
valueMap[id] = valueObject;
}
function someFunction(id) {
return valueMap[id].Value;
}
This makes no sense:
someVariable = document.getElementById(SomeID).id
You are fetching the id of the element with id SomeID...why not just use SomeID?
If you want the value attribute of the object with id SomeID, just do:
document.getElementById(SomeID).value

Categories

Resources