0

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;
            };
5
  • Since carlike isn't a method, you need something like carlike.call(obj, loc) to set the value of this. Then, carlike(obj, loc) is probably a better approach in this case. Commented Dec 11, 2014 at 1:29
  • In the first one, where it says obj.move = move; is that supposed to be this instead of obj? Commented Dec 11, 2014 at 1:31
  • @Pointy, you are right. I made the edit. Commented Dec 11, 2014 at 1:35
  • Should return obj in the first one be return this? Commented Dec 11, 2014 at 1:38
  • @Barmar, I believe you are right. Made the correction. Thank you. Commented Dec 11, 2014 at 1:46

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.