KishB87
KishB87

Reputation: 303

This vs Defining Object in Function Argument in Javascript

Below you will find two different decorator patterns. One uses "this" while the other one defines the object in the function arguments.

What is the advantage of defining the object vs using "this" from a memory/performance perspective? When is it appropriate to use this rather then defining the object?

//Using this in the object
    var carlike = function(loc) {
                this.loc = loc;
                var move = function() {
                    this.loc++;
                };
                this.move = move;
                return this;
            };

//Defining the object in the arguments
    var carlike = function(obj, loc) {
                obj.loc = loc;
                var move = function(obj) {
                    obj.loc++;
                };
                obj.move = move;
                return obj;
            };

Upvotes: 0

Views: 58

Answers (1)

Bergi
Bergi

Reputation: 664164

For the carlike function, there is no performance difference. However, as you say it is a decorator - which would be called as a static function on an object - not a constructor or method. You would want to use carlike({}, 0) instead of carlike.call({}, 0), so go with the second pattern.


For the move function, there is a memory difference. The pattern with obj creates a closure, which costs more than the this in the first pattern. Which one to choose is a different question, as they simply act different.

If you would want to optimize memory consumption, you could further improve the first pattern by not creating new move functions on every invocation of carlike. Just do

function move() {
    this.loc++;
}
function carlike(obj, loc) {
    obj.loc = loc;
    obj.move = move;
    return obj;
}

Upvotes: 1

Related Questions