为什么我得到未定义的构造函数

为什么我得到未定义的构造函数

问题描述:

我尝试跟随Stephan Stoyanov关于JavaScript设计模式的书。本书中的一个示例与此类似:

I try to follow Stephan Stoyanov book on JavaScript Design Patterns. And one of the examples in this book looks similar to this:

var MyClass = (function () {
    var Constr, cnt = 0;
    Constr = function () {};    
    Constr.id = function () {
        return "myid-" + cnt;
    };
    Constr.prototype = {
        constructor: MyClass // <-- Please, pay attention
    };
    return Constr;
}());

但是,当我像这样使用这个代码时:

However, when I use this code like so:

var tst = new MyClass();
console.log(tst.contructor);

我在控制台中看到 undefined 。为什么这样,我该如何解决?

I see undefined in the console. Why is that and how can I fix that?

在您分配 MyClass $的时候c $ c>到原型的 .constructor 属性,变量 MyClass 尚未初始化。在函数执行完之后,它才会有值。相反,您可以只分配 Constr ,因为它确实有一个值,它们将是最终分配给 MyClass $ c的相同值$ c>。

At the point you assign MyClass to the .constructor property of the prototype, the variable MyClass has not yet been initialized. It won't have a value until after your function is done executing. Instead, you can just assign it Constr since that does have a value and they will be the same value that is eventually assigned to MyClass.

var MyClass = (function () {
    var Constr, cnt = 0;
    Constr = function () {};    
    Constr.id = function () {
        return "myid-" + cnt;
    };
    Constr.prototype = {
        constructor: Constr // <-- Change to this
    };
    return Constr;
}());