JavaScript - IIFE中的构造函数

时间:2014-03-06 14:01:34

标签: javascript

为什么下面的代码不会返回Person对象?它改为返回undefined fiddle

var factory = (function () {
        function Person(name, salary) {
            this.name = name;
            this.salary = salary;
        }
        Person.prototype.talk = function () {
            console.log('talking...');
        }
        return {
            Person: Person
        }

    })();
    var x = factory.Person('me', 100);
x.talk(); //cannot read property talk of undefined

3 个答案:

答案 0 :(得分:3)

因为它不是一个合适的工厂:

var factory = (function () {
        function Person(name, salary) {
            this.name = name;
            this.salary = salary;
        }
        Person.prototype.talk = function () {
            console.log('talking...');
        }
        return {
            Person: function(name,salary){
              return new Person(name,salary);
            }
        }

    })();
    var x = factory.Person('me', 100);
x.talk(); //cannot read property talk of undefined

如果你不在Person上调用new,那么就没有原型继承。

编辑:你可以在工厂方法上更抽象,这样你就可以在不影响工厂的情况下改变构造函数的参数

return {
   Person:function(){
        return  new (Function.prototype.bind.apply(Person,arguments));
        }
}

或使构造函数成为impllcit工厂

       function Person(name, salary) {
            if(!(this instanceof Person)){
              return new (Function.prototype.bind.apply(Person,arguments));
            }
            this.name = name;
            this.salary = salary;
        }

答案 1 :(得分:2)

var x = factory.Person('me', 100);会调用factory.Person()(仅设置this.namethis.salary并且不返回任何内容,因此undefined)。

您想使用new关键字:

var x = new factory.Person('me', 100);
//      ^^^

Fiddle

答案 2 :(得分:2)

已经发布了相应的答案,但我只想通过确保构造函数始终返回Person的新实例来显示实现相同结果的不同方法,即使new是遗忘。

var factory = (function () {
        function Person(name, salary) {
            if (!(this instanceof Person)) return new Person(name, salary);

            this.name = name;
            this.salary = salary;
        }
        Person.prototype.talk = function () {
            console.log('talking...');
        }
        return {
            Person: Person
        }

    })();
    var x = factory.Person('me', 100);
x.talk();