Cant use prototype if constructor return object

Can somebody explain me this:

var foo = function() {
  if (!(this instanceof foo))
    return new foo();
  return {}; // Object
};
foo.prototype.myPlugin = function () { // Uncaught TypeError: foo(...).myPlugin is not a function
  alert("bar")
};

foo().myPlugin();

but:

var foo = function() {
  if (!(this instanceof foo))
    return new foo();
  return ""; // string, number, etc
};
foo.prototype.myPlugin = function () {
  alert("bar") // --> "bar"
};

foo().myPlugin();

as i see, jquery works like first code sample, and returns array of finded DOM nodes. But when i try return array, i have this error too.

Upvotes: 2

Views: 55

Answers (2)

Paul
Paul

Reputation: 141839

If you return an object from a constructor that will be returned instead of the object created by new. If you return any other type, your return value will be ignored and the new object will be returned instead.

jQuery doesn't return an array of DOM elements. The jQuery object is just array-like itself. It has some numeric properties, a length property, and a splice method, which is all it takes for you to be able to access elements like obj[0] and for a console to log it like an array.

Upvotes: 1

udnisap
udnisap

Reputation: 909

This is the way the javascript is. In a constructor if you return a primitive type it returns the constructed object instead. Simply the primitive value is ignored. If it returns an object it returns that object.

For example

function ReturnsObject(){ return {}; }
function ReturnsPrimitive(){ return 5 // 'string'; }
console.log( new ReturnsObject()) // {}
console.log( new ReturnsPrimitive()) // ReturnsPrimitive{}

Upvotes: 0

Related Questions