nicholas
nicholas

Reputation: 14563

extending Function

I've been seeing the syntax:

var module = {

    func: function(value) {

        some code;

    }.func2("value");

}

cropping up in various places, as am wondering how this is done. I remember seeing an article about it a while back, but can't find it now. Whatever I try .func2("value") just trows syntax errors.

For example, take a look at SproutCore's intro to their TemplateView.

Todos.StatsView = SC.TemplateView.extend({
  remainingBinding: 'Todos.todoListController.remaining',

  displayRemaining: function() {
    var remaining = this.get('remaining');
    return remaining + (remaining === 1 ? " item" : " items");
  }.property('remaining').cacheable()
});

Seems like it would be a useful tool to give users when writing factories.

Thanks.

Upvotes: 1

Views: 914

Answers (3)

nicholas
nicholas

Reputation: 14563

You can add properties to Function's prototype and then chain function definitions. For example:

Function.prototype.trigger = function(trigger) {

    var setValue = this;

    return function(thevalue) {
        alert(trigger + ' set to ' + thevalue);
        setValue(thevalue);
    };

};

var _value = 0;

var setValue = function(thevalue) {

    _value = thevalue;

}.trigger('value');

setValue(25);

When setValue is defined the trigger function is called within the scope of the anonymous function it's chained to, and setValue is assigned the value returned by trigger. In this case we're just alerting that setValue is being called, but this opens some very cool possibilities.

Pretty slick.

Upvotes: 1

gion_13
gion_13

Reputation: 41533

that's kind'a weird.Maby is was something like :

var module = {
    func : (function(){
        return {func2 : function(v){alert(v);}};
    }).func2('alert me');
}

you cannot chain function definitions (function func (){}.func1()),only function calls (if configured properly) that would look like : func1().func2().func3().....

Upvotes: 0

Quentin
Quentin

Reputation: 943214

The syntax I think you are looking for it is:

func: (function(value) {
    //some code;
}("value"));

In which the anonymous function is called immediately and its return value assigned to func.

See also: How do JavaScript closures work?

Upvotes: 0

Related Questions