在JavaScript中使用相同的名称 [英] functions with same names in javascript

查看:78
本文介绍了在JavaScript中使用相同的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个js文件上写一个函数,并在页面中使用另一个同名的函数。我期待一个错误,但没有错误,我只从js文件中执行函数。这是可能的。即使我在一个单独的js文件中编写函数,所有东西都会呈现在一个单独的html文件中。那么如何才能实现这一点?

I tried to write a function on a js file and another function with the same name in the page.I expected an error but no error came and i got only the function from the js file to execute.How is this possible.Even if i write a function in a separate js file,everything is rendered in a single html file.Then how come it is possible

<script type="text/javascript" language="javascript" src="JScript.js" />
<script language="javascript">
    function Boo()
     {
        alert("Hai new");
    }
</script>

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button runat=server OnClientClick="Boo();" Text="Click" />
    </div>
    </form>
</body>

和js文件

function Boo() {
    alert("Hai");
}


推荐答案


没有多少人想过使用JavaScript的一个方面是
,如果您定义多个函数
具有相同的名称,那么最后一个定义的
将是实际上
运行。 JavaScript函数不是
多态的,
中的函数的方式很多其他语言都在
中JavaScript不关心为函数
定义的实际
参数是否不同的是,在此基础上它们不能区分它们之间的
。在
其他语言中,您可能有
myfunc(oneparm)和myfunc(parmone,
parmtwo)作为两个独立函数
,其中运行的函数取决于

中传递的参数数量JavaScript定义的最后一个参数
始终是一次运行,不管
是多少个参数。

One aspect that not many people ever think about with JavaScript is that if you define multiple functions with the same name then the last one defined will be the one that actually runs. JavaScript functions are not polymorphic the way that functions in many other languages are in that JavaScript doesn't care if the actual arguments defined for the functions are different as it can't distinguish between them on that basis. Where in other languages you might have myfunc(oneparm) and myfunc(parmone, parmtwo) as two separate functions with the one that gets run depending on the number of parameters passed, in JavaScript the last one defined will always be the one run regardless of the number of parameters.

http://javascript.about.com/library/blpolyfunc .htm

这篇关于在JavaScript中使用相同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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