问题
Is there any way to create\return a pointer to variable in JavaScript ?
like, in PHP :
function func() {
.....
return &$result;
}
I have a JS function like:
function(...) {
x=document.getElements..... //x is HTML tag
if (x.localName=='input') return x.value //String variable
else if (x.localName=='textarea') return x.innerHTML //String variable
}
Using this function, I can get a copy of the data from x, but not to change the source.
I want possibility to change it too.
Thanks
回答1:
Hej Dani-Br
you can do something like this
function(...) {
var x = document.getElements..... //x is HTML tag
if (x.localName=='input') return {
get: function() { return x.value },
set: function(v) { x.value = v; }
};
else if (x.localName=='textarea') return {
get: function() { return x.innerHTML },
set: function(v) { x.innerHTML = v; }
};
}
so that the caller can set and get the value. ps. use var to declare local vars
GL
回答2:
No, you can't return a pointer to a string. In Javascript Objects are assigned and passed by reference automatically, and primitives are copied. So if you return x;
then you can modify x.innerHTML
, but if you return x.innerHTML
the string will be copied.
回答3:
Primitive types are passed by value. Objects are passed by reference. I guess x.innerHTML is a string, so it is passed by value.
Take a look at this piece of code, it shows you passing objects by reference:
function test(str){
return str;
}
var k = { txt : 'foo' },
n = test(k);
console.log(n.txt);
k.txt = 'bar';
console.log(n.txt);
回答4:
This might not be exactly what you are looking for but one thing that hasn't been brought up yet is that inner functions can access the variables of their outer functions:
function myFunc(){
var x = "hello";
myInnerFunc();
function myInnerFunc (){
//shows the variable of the outer function
console.log(x);
};
};
Additionally you can use a closure to save the state of an outer functions variables:
function myFunc2(){
var x = "hello";
var timesCalled = 0;
return function (){
timesCalled++;
console.log(x + " called: " + timesCalled);
};
};
var fun = myFunc2();
fun(); //1
fun(); //2
fun(); //3
来源:https://stackoverflow.com/questions/7660413/pointer-to-variable-in-javascript