Brent
Brent

Reputation: 4876

why declare empty javascript function and then add properties

This code from ryan niemeyer on this blog bost declares an empty function(named result) and then adds properties to the function:

ko.dirtyFlag = function(root, isInitiallyDirty) {
    var result = function() {},
        _initialState = ko.observable(ko.toJSON(root)),
        _isInitiallyDirty = ko.observable(isInitiallyDirty);

    result.isDirty = ko.computed(function() {
        return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
    });

    result.reset = function() {
        _initialState(ko.toJSON(root));
        _isInitiallyDirty(false);
    };

    return result;
}; 

What advantage does this serve over simply creating an object and assigning the same properties before returning the object?

edit

in response to the comment requesting how i would expect it to look: either declaring

var result={};

in the declarations, or as a style thing:

ko.dirtyFlag = function(root, isInitiallyDirty) {
    var _initialState = ko.observable(ko.toJSON(root)),
        _isInitiallyDirty = ko.observable(isInitiallyDirty);
    return {
      isDirty : ko.computed(function() {
        return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
      }),
      reset : function() {
        _initialState(ko.toJSON(root));
        _isInitiallyDirty(false);
      }
   };
}; 

but the semantics are irrelevant - what does a shell of a function returned provide to the consuming code/developer calling the function?

Upvotes: 2

Views: 123

Answers (2)

harmic
harmic

Reputation: 30577

In the link you posted, the author states

When ko.toJS runs, it will just see a plain function and ignore it.

In other words, he is using the fact that the framework he is using will ignore functions in the context where he is using it, whereas if he had used an object the framework would not ignore it.

He never intends to call the function, just to use it as a place to store his dirty flag while tricking the knockout framework into ignoring it.

Upvotes: 5

Dory Zidon
Dory Zidon

Reputation: 10719

It's just another way to create an object, I do not believe it has any difference to doing it one way or another. sometimes just a style preference, sometime just the way a programmer likes to do something. (just like using var that = this, or using a function's bind method. both legit and both ways of passing context).

Here is a detailed post on creating objects in JavaScript from MDN

Creating an object and declaring an empty function in JavaScript are way to create an object. In JavaScript things are objects and there are many ways to create them. No one way is much better than the other. Although from ECMAScript5 the better way to do it is Object.create.

Upvotes: 1

Related Questions