views:

36

answers:

3

Dear experts,

I am trying to assign an function within an function object property without actually invoking then function itself.

for instance,

I have the following function object class definition

function objectOne(name, value, id){
    this.name=name;
    this.value=value;
    this.id=id;
    this.methodOne=methodFunction(this);
}

the last line this.methodOne=methodFunction(this); I want to pass the current object to the function but at the same time i don't want to execute the function right now.

But if I do it this way without the bracket this.methodOne=methodFunction then the argument of this object would not be passed as a parameter to the function.

Is there a way to work through this.

Thank you in advance

A: 

You could do it this way

function objectOne(name, value, id){
    this.name=name;
    this.value=value;
    this.id=id;
    this.methodOne=function() { methodFunction(this); };
}
Kunal
thank you i thought of that but I am building a large application where this would be an generic function object definition. Each instance of this object be unique and have its own set of method. Is there another way?
Dennis D
Probably you should use protoype. This way you would not be creating functin for each object. ObjectOne.prototype.methodOne = function(){ methodFunction( this );}
Kunal
do you mean prototype the javascript library? Or just the genertic native prototype technique of core JS
Dennis D
generic prototype technique of core JS
Kunal
With generic prototype technique, each instance of this *class* would not be having own set of "methodOne" function. Instead the same function would be called with the scope of current object.
Kunal
+1  A: 

This page helped explain this concept to me the best. Essentially would be doing something like the following.

function objectOne(name, value, id) {
  function methodFunction(value) {
     // do something
  }

  var that = this;

  this.methodOne = function() {
     methodFunction(that);
  };
}

var x = new objectOne("one", 2, 3);
x.methodOne();
Dave
A: 

This sort of thing is what "curry" is for. Either use curry() from your favorite JS library, or make your own:

function curry (func, what_this) {
    var what_this = what_this || window;
    var args = [];
    for (var i=2, len = arguments.length; i < len; ++i) {
        args.push(arguments[i]);
    };
    return function() {
        func.apply(what_this, args);
    };
}

Then the last line of your constructor looks like this:

this.methodOne=curry(methodFunction, undefined, this);
Mark Bessey