<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/