Please excuse the question title; I can't find a better way to phrase this.
I stumble upon this article when reading JavaScript design patterns by Addy Osmani. Apart from 2 common ways to represent a class in JavaScript, which is to use a function and a object literal, the author gives an example of combining the two in what looks like an inline invocation. So far so good, except I can't pass parameters to the constructor:
var apple = new function() {
this.type = "macintosh";
this.color = "red";
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
}
// can't do new function("red") obviously
I thought of a way around the problem
var apple = (function(color) {
this.type = "macintosh";
this.color = color;
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
return this;
})("red");
But it seems a bit convoluted and I prefer the use of "new", which is related to this problem discussed by John Resig. As I have returned a reference to the object, it'll still work but looks very ugly. Is there anyway I can still use the new operator with parameters for constructor in this case?
new function(){...}, I guess that you don't need to do something likeif(apple instanceof APPLE)later, so why not simply return an object ({type:"macintosh",...})?newis quite "bad" in Douglas Crockford's view.