Reputation: 4873
I'm writing a JS function that I would like to be used directly with an onfocus event, and also within another function. The problem is that if I pass the function this, then all of my function code needs to be field.value. That causes a problem when I use it inside a function, since the passed variable doesn't have a .value attribute.
My thought was then to just pass this.value to the function, so I could just work with the data passed, whether it was a field value or a function value. However, now it doesn't change the value of the original field.
Is there a good way around this, or do I just need to have two functions?
Here is my two different versions of the code:
// Can't be used with when using onfocus="makeNum(this.value)"
function makeNum(value){
value = value.match(/\d+(\.\d{1,2})?/g).join("");
}
OR
// Can't be used with a function, but works when using makeNum(this)
function makeNum(field){
field.value = field.value.match(/\d+(\.\d{1,2})?/g).join("");
}
Upvotes: 0
Views: 1326
Reputation: 707656
If you showed the two flavors of desired code, we could probably help a lot more specifically. Objects are passed by reference, but individual variables are not so you can't have the same behavior for both.
Your options I can think of are this:
Pass an object into the function as an argument then refer to obj.value
in order to change the actual value on the original object.
Pass a callback function to your main function that operates on the object and you can then have several different ways of setting the value from the same core code.
Break your core function up into smaller functions that can be called from different places and used in different ways when operating on different types of source data.
Write a single function that can tell from its arguments which type of data you are passing to it and operate accordingly.
In the case of your code examples, here's the core function that you can use in a couple different ways:
function makeNum(value){
return(value.match(/\d+(\.\d{1,2})?/g).join(""));
}
x.onfocus = function() {
this.value = makeNum(this.value);
}
Upvotes: 1
Reputation: 24362
Objects are passed by reference, but primitives are passed by value. Since this.value
is a primitive (i.e. a string or number for example), it will be copied when you pass it to the function, and modifications to it only apply the the function.
Write the function so it returns a value, then assign it back to this.value
like this:
this.value = makeNum(this.value);
function makeNum(value){
return value.match(/\d+(\.\d{1,2})?/g).join("");
}
Upvotes: 3