Sagi_Avinash_Varma
Sagi_Avinash_Varma

Reputation: 1509

Unable to use callback function as an object method

object methods are generally declared and used like this

points = { 
  first : function(){
    return this.val[0];
  }
};
points.val = [1,2];
points.first(); // returns 1

But why am i not allowed to use callbacks instead of a declared method.

points.val = [1,2];
points.(function(){
    return this.val[0];
  })();

Upvotes: 1

Views: 77

Answers (3)

Gabs00
Gabs00

Reputation: 1877

You can by defining a function on points that takes a callback

var points = {val:[1,2]};
points.func = function(callback){
    callback.call(this);
}

And call it with

points.func(function(){
    return this.val;
})

You can't use a function as the object key, but you can add a function to the object. You can also define a function outside of the object and use the .call or .apply methods

function val(){
    return this.val;
}

val.call(points);

Upvotes: 1

joews
joews

Reputation: 30330

Calling a method on an object consists of two steps:

  1. Looking up an object property by key
  2. Executing the returned property (which must be a function, or a TypeError is raised).

In your first example, your calling code uses the . syntax to retrieve the property of points with key first. It then executes the returned property, which is an anonymous function.

In your second example you are attempting to look up an object with the key:

(function(){
  return this.val[0];
})

In JavaScript, Object keys must be valid identifiers. Function expressions are not valid identifiers, so the compiler raises a SyntaxError.

If you're trying to use a dynamically defined function that uses this to refer to points, you use bind:

(function() { return this.val[0] }).bind(points)()

Upvotes: 1

MartinWebb
MartinWebb

Reputation: 2008

I think what you are trying to do is make a getter/setter for points.

points={};

// pass in an array to set points or pass a callback to retrieve them!
points.val = function (points){
//test if points is a callback return points to callback
if (typeof points==="function") return points(this._points); 
// or set the points with the passed in value
this._points=points;
};

//set the points
points.val([1,2])

//get points into callback

points.val(function(e){
    return e[0];
});

Upvotes: 0

Related Questions