Frage

function Cons()
    {
        this.a = "variable a";
        this.callme = function callme()
        {
            var str = "";
                for(var x in this)
                {
                    str += this[x] + " ";
                }
            return str;
        }
    }

    var obj = new Cons();

    obj.c = "variable 2";

    var fin = obj.callme();
    document.write(fin);

I want to have a function inside the object so that when it is called it can return a string consisting of the values of every member. Here in this case a and c. Now what happens, everything inside the function i mean the code is printed inside the browser instead of just returning the value of str.

What i understood is that this["callme"] part in the for-in loop returns the whole code as its also a variable. So how to solve this problem.

I am new to javascript please help me.

War es hilfreich?

Lösung 2

If you want to avoid the function body being printed, check if the property is a function and print only its name:

this.callme = function callme()
    {
        var str = "";
            for(var x in this)
            {
                if ('function' === typeof this[x]) {
                    str += x + " ";
                } else {
                    str += this[x] + " ";
                }
            }
        return str;
    }

Andere Tipps

There are several ways to solve this:

1) Remove callme from the for..in :

for(var x in this) {
  if (x !== 'callme') {
    str += this[x] + " ";
  }
}

2) Declare callme as a non-enumerable property:

function Cons() {
    Object.defineProperty('callme', {
      enumerable : false,
      value : function callme() {
        var str = "";
            for(var x in this)
            {
                str += this[x] + " ";
            }
        return str;
      }
    });
}

3) Change the toString method of callme to return nothing:

function Cons() {
    this.a = "variable a";
    this.callme = function callme() {
        var str = "";
            for(var x in this)
            {
                str += this[x] + " ";
            }
        return str;
    }
    this.callme.toString = function(){ return '';};
}

The simplest solution is the first one, but the others are too interesting to pass.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top