为什么我得到未定义的构造函数 [英] Why do I get undefined constructor

查看:111
本文介绍了为什么我得到未定义的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试跟随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 到原型的 .constructor 属性,变量 MyClass 尚未初始化。在函数执行完之后,它才会有值。相反,您可以只分配 Constr ,因为它确实有一个值,它们将是最终分配给 MyClass

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;
}());

这篇关于为什么我得到未定义的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆