我正在做一个小网站,我需要使用 javascript。我对原型(prototype)函数有疑问。我正在测试一些东西,我意识到每当我加载页面时,我的函数的原型(prototype)总是会执行。我有这个代码:
function Clinica ()
{
var id = 0;
var doentes = [];
}
Clinica.prototype.criarDoente = new function ()
{
alert("HELLO");
}
该警报仅用于测试。现在我有这个 HTML :
<form id ="criarDoenteForm" onsubmit = javascript: "criarDoente();" >
<label> Número: </label>
<label id ="numero"> </label>
</br>
<label> Nome: </label>
<input type="text" size="20" />
</br>
<label> Sexo: </label>
<input id="masculino" name="sexo" type="radio" value="m" />
<label for="masculino" class="valores">Masculino </label>
<input id="feminino" name="sexo" type="radio" value="m" />
<label for="feminino" class="valores"> Feminino </label>
</br>
<label> Data de Nascimento: </label>
<input type="text" size="10" />
</br>
<input type="submit" value="Criar" />
<input type="submit" value="Cancelar" />
</form>
所以,当我单击提交按钮时,它会运行该函数并且确实如此。但是,每当我刷新页面或打开它时,它总是会加载。这是为什么?
最佳答案
正如 Daniel A. White 指出的那样,新
就是问题所在。
当您将 new
放在函数之前时,它将执行该函数,并将其用作新对象的构造函数。即使没有任何括号来调用该函数,也会发生这种情况。
你在这里做什么:
Clinica.prototype.criarDoente = new function ()
{
alert("HELLO");
}
与以下内容本质上具有相同的效果:
var f = function ()
{
alert("HELLO");
};
Clinica.prototype.criarDoente = new f; // <-- this will execute the function
// even without parentheses
所以只需删除new
:
Clinica.prototype.criarDoente = function ()
{
alert("HELLO");
};
关于Javascript 原型(prototype)函数总是加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27669696/