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

标签 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>

为什么它告诉我 CustomAlert 未定义?我还尝试将 CustomAlert() 分配给一个 var,但随后控制台告诉我该 var 现在未定义。

最佳答案

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

function HighScore( arg )
{
    new CustomAlert().render();
}

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

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

    return obj;
}

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

function HighScore( arg )
{
    CustomAlert().render();
}

关于javascript - 为什么我的函数调用不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28397414/

相关文章:

javascript - 在页面渲染之前更改 HTML 数据

javascript - 如何获取触发 easyautocomplete 的元素

javascript - 重新创建 Visual Studio 项目文件

javascript - window.open(url).print() 在 Safari 中不起作用

php函数保存文本输入同名变量分隔

MySQL,创建一个简单的函数

c# - 用于解析 C/C++ 函数声明的正则表达式

javascript - 优化 if else 条件 javaScript

python - 为 LabVIEW 在 Python 中返回图像的问题

r - 使用 "..."R 拆分函数的数组参数