Is there an equivalent to instance_eval in JavaScript?

No, I don't think so. But you can probably add it.

        Object.prototype.instance_eval = function(code_or_function) {
          var func = null;
          if(typeof(code_or_function) == "function") {
            func = code_or_function;
          } else if(typeof(code_or_function) == "string") {
            func = function() { eval(code_or_function); }
          }
          if(func) {
            return func.apply(this);
          }
        }
                var o = { helloPhrase : "hello" };
        o.instance_eval(function() {
          alert(this.helloPhrase);
        });
                o.instance_eval("alert(this.helloPhrase);");

Although you might not want to add it to Objects prototype and do it as a function that takes the receiving object as a parameter. I'm also not 100% sure that this captures the full semantics of instance_eval altough I guess it's quite close.

/Marcus

Thanks, Marcus! I'll let you know if some corner cases crop up (my
JavaScript is pretty rusty).

BTW, what is it with JavaScript and guys from Sweeden? :slight_smile:

Cheers,
-John

···

On 5/18/06, Marcus Andersson <m-lists@bristav.se> wrote:

No, I don't think so. But you can probably add it.

        Object.prototype.instance_eval = function(code_or_function) {
          var func = null;
          if(typeof(code_or_function) == "function") {
            func = code_or_function;
          } else if(typeof(code_or_function) == "string") {
            func = function() { eval(code_or_function); }
          }
          if(func) {
            return func.apply(this);
          }
        }

        var o = { helloPhrase : "hello" };
        o.instance_eval(function() {
          alert(this.helloPhrase);
        });

        o.instance_eval("alert(this.helloPhrase);");

Although you might not want to add it to Objects prototype and do it as
a function that takes the receiving object as a parameter. I'm also not
100% sure that this captures the full semantics of instance_eval altough
I guess it's quite close.

/Marcus