tags:

views:

103

answers:

1

make this:

/*this can't run*/
var o = {first:1};
function f(arg,o){
   /*
    can i do something make this function's this=o
   */
   alert(arg+this.first);
}
f(2,o);

equal this:

var o = {
  first:1,
  f:function(arg){
    alert(arg+first);
  }
}
o.f(2);

and I know we can use this:

f.apply(o,1);

but I want to handle all things in f:

function f(arg,o){
    /*magic*/
    alert(arg+this.first);
}
+3  A: 

Is this what you mean:

var o = 
{ 
  first : 1, 
  f : function(arg)
  { 
    alert(arg + this.first);
  }
}
Matthew Flaschen
+1 Bravo for understanding what was asked!
Abel
I think the OP wants to bind the globally declared function `f` to `o`'s scope.
Ates Goral
Yes, that's what i want to say...Thank you~I want to know if i can change a function's scope to one of it's parameters.
CunruiLi
It doesn't make sense to change `this` to a parameter to the function. If you have access to the function's source, you might as well access the other object's properties directly as `o.prop` instead of `this.prop`. But, you can certainly create a new function that is bound to a given scope. See my comment to your original question.
Ates Goral
thank you very much.That's what i want to do.Now I can use f like this:[code]xhrPost("url",load:f);//now f can handle responseText in o[/code]
CunruiLi