【问题标题】:Is it not possible for a function to return a constructor and create a new instance?函数不可能返回构造函数并创建新实例吗?
【发布时间】:2014-12-20 22:02:26
【问题描述】:

我有以下 JavaScript 代码,由一个函数和两个构造函数组成:

function get_type(type){
    switch(type){
        default: case "a": return apple; break;
        case "b": return banana; break;
    }
}

function apple(color){
    this.color = color;
    this.age   = 0;
}

function banana(length,unit){
    this.length = length;
    this.unit   = unit||"cm";
    this.age    = 0;
}

当我尝试创建一个值为new get_type("a")("red") 的变量macintosh 时,它的值为undefined,甚至认为get_type("a") 成功返回了apple 构造函数。

是我的代码有问题,还是不可能有返回构造函数的函数?

编辑:变量macintosh的构造。

var macintosh = new get_type("a")("red")

【问题讨论】:

    标签: javascript object constructor


    【解决方案1】:

    您的问题是 new 运算符的特殊性。你的代码基本上是这样的:

    var macintosh = (new get_type("a"))("red")
    

    创建get_type 类型的对象,然后将参数传递给它。你想要的是这样的:

    var macintosh = new (get_type("a"))("red")
    

    先获取构造函数,再使用。

    【讨论】:

    • 完美!这就说得通了。到时候我会接受的。
    【解决方案2】:

    您必须发出new 才能创建新实例。

    function get_type(type){
    switch(type){
        default: case "a": return new apple(); break;
        case "b": return new banana(); break;
     }
    }
    

    【讨论】:

    • 使用var macintosh = new get_type("a")("red");,我收到错误TypeError: ({color:(void 0), age:0}) is not a function
    • 按照我的回答做,你的代码没有返回一个实例,你正在返回一个函数的引用。
    猜你喜欢
    • 2013-07-20
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多