简体   繁体   中英

Passing parameter to object created with inline invocation using new in JavaScript

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?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM