admin管理员组

文章数量:1287894

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

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

Share Improve this question asked Oct 5, 2011 at 11:14 Dani-BrDani-Br 2,4575 gold badges26 silver badges33 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

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.

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

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);

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

本文标签: dompointer to variable in JavaScriptStack Overflow