seebiscuit
seebiscuit

Reputation: 5053

Underscorejs changes function to object

Edit: I realized I passed MyConstructorFunc.prototype to `_.extend().

I ran into an interesting implementation detail when I wanted to extend a function with Underscore.

I built a function constructor,

var MyConstructorFunc = function() {
  ...
}

then I returned the result of

return _.extend(MyConstructorFunc.prototype, {
  \\ ...some properties...
}

What I got back was a typeof MyConstructorFunc == "object"! If _.extend is merging properties into a function why does it return an object?

Looking at the _.extend function I don't see where that happens...

_.extend = function(obj) {
    if (!_.isObject(obj)) return obj;
    var source, prop;
    for (var i = 1, length = arguments.length; i < length; i++) {
      source = arguments[i];
      for (prop in source) {
        if (hasOwnProperty.call(source, prop)) {
            obj[prop] = source[prop];
        }
      }
    }
    return obj;
  };

If I do MyConstructorFunc["someProp"] = someObject["someProp"] and return MyConstructorFunc, I returned a JavaScript object?

I'm missing something...

Upvotes: 0

Views: 51

Answers (1)

Brian Tovar
Brian Tovar

Reputation: 344

You are probably passing in a Function object to _.extend. Your sample code does not show it, but if you are making a new instance of your MyConstructorFunc using the "new" keyword, then the result will be an object.

var MyConstructorFunc = function() {
}

var foo = _.extend(MyConstructorFunc, {a:1});
console.log(typeof foo); // function 

var funcObj = new MyConstructorFunc();
console.log(typeof funcObj); //object

Extending the MyConstructorFunc itself will return a function type. It's once you use the contructor to create a new function that you are given an object.

Upvotes: 2

Related Questions