将参数传递给使用 JavaScript 中的 new 通过内联调用创建的对象

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

本文关键字:调用 创建 对象 new 参数传递 中的 JavaScript      更新时间:2023-09-26

请原谅问题标题;我找不到更好的表达方式。

我在阅读 Addy Osmani 的 JavaScript 设计模式时偶然发现了这篇文章。除了在 JavaScript 中表示类的 2 种常见方法(即使用函数和对象文字)之外,作者还给出了一个将两者组合在一起的示例,看起来像是内联调用。到目前为止一切顺利,除了我无法将参数传递给构造函数:

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

我想到了解决问题的方法

var apple = (function(color) {
    this.type = "macintosh";
    this.color = color;
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
    return this;
})("red");

但这似乎有点令人费解,我更喜欢使用"new",这与John Resig讨论的这个问题有关。由于我返回了对该对象的引用,它仍然可以工作,但看起来非常丑陋。在这种情况下,我仍然可以将带有参数的新运算符用于构造函数吗?

我个人会通过将类定义为变量,然后使用 new 关键字创建它的实例来做到这一点,如下所示:

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