为什么我的函数调用不起作用?

Kev*_*son 3 javascript function

<script type="text/javascript">
    function CustomAlert() {
        this.render = function() {
            var winW = window.innerWidth;
            var winH = window.innerHeight;
            var dialogOverlay = document.getElementById('dialogOverlay');
            var dialogbox = document.getElementById('dialogbox');

            dialogOverlay.style.display = "block !important ";
            dialogOverlay.style.height = winH+"px !important ";
            dialogbox.style.left = (winW/2) - (550 * .5) + "px !important ";
            dialogbox.style.top = "100px !important ";
            dialogbox.style.display = "block !important";
        }

        this.ok = function () {
        }
    }

    function HighScore( arg )
    {
        CustomAlert().render();
    }
</script>
Run Code Online (Sandbox Code Playgroud)

为什么告诉我这CustomAlert是不确定的?我也尝试分配CustomAlert()给var但是控制台告诉我var现在是未定义的.

p.s*_*w.g 5

当被称为普通函数(CustomAlert())时,您的函数不会返回任何内容.但是,您可以在调用函数时使用运算符将其作为构造函数function(new CustomAlert())new调用.这将导致this函数内部引用新创建的对象实例并自动将该实例用作返回值:

function HighScore( arg )
{
    new CustomAlert().render();
}
Run Code Online (Sandbox Code Playgroud)

另一种(但肯定不是等价的)解决方案是直接从CustomAlert以下位置返回一个新对象:

function CustomAlert() {
    var obj = {
        render: function () {
            ...
        },
        ok: function () {
            ...
        }
    };

    return obj;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以像普通函数一样调用它:

function HighScore( arg )
{
    CustomAlert().render();
}
Run Code Online (Sandbox Code Playgroud)