0

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?

3
  • Since you tried to use new function(){...}, I guess that you don't need to do something like if(apple instanceof APPLE) later, so why not simply return an object ({type:"macintosh",...})? new is quite "bad" in Douglas Crockford's view. Commented Sep 12, 2013 at 6:57
  • 1
    The syntax you're using is described in the article as being for a singleton class. Singletons don't need a parameter, since there's only one instance and you can hard-code the properties. Commented Sep 12, 2013 at 6:58
  • 1
    See the patterns in section 1 of the article. Commented Sep 12, 2013 at 6:59

1 Answer 1

1

I would personally go about this by defining the class as a variable, and then creating instances of it with the new keyword, like so:

var Apple = function(color) {
    this.type = "macintosh";
    this.color = color;
}

var redApple = new Apple("red");
Sign up to request clarification or add additional context in comments.

2 Comments

This undoubtedly works. The thing is when you want to add function to the object, you'll have to add to its prototype if you choose to create this way. As the author pointed out, a benefit with the inline new is that you can add to the object itself (apple.getInfo vs Apple.prototype.getInfo).
@LimH. You can always add method/property to an object itself, not limited to its constructor's prototype: ideone.com/lK9bdB

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.