[英]Why am I able to define same function twice in javascript?
I have a javascript file in which I write a bunch of jquery functions.我有一个 javascript 文件,我在其中编写了一堆 jquery 函数。 I have a function to return the angular scope.我有一个函数来返回角度范围。 I found out that if I were to write the same function twice, the code still executes.我发现如果我要写两次相同的函数,代码仍然会执行。
function getngScope()
{
alert(2);
return angular.element($('#data-area')).scope();
}
function getngScope()
{
alert(1);
return angular.element($('#data-area')).scope();
}
When I call getngScope()
I get "1" alerted and the scope returned.当我调用getngScope()
我收到“1”警报并返回范围。 Why does it have this behavior?为什么会有这种行为?
The second definition of an Object overwrites the first one.对象的第二个定义覆盖了第一个。 In general the last definition of an object overwrites all previous definitions.通常,对象的最后定义会覆盖所有先前的定义。
Functions in JavaScript are Objects: JavaScript 中的函数是对象:
(function () {}) instanceof Object === true
When you create a new global function f
it's equivalent to creating a property in the window
object and assigning the function definition to that variable, if you create a function:当您创建一个新的全局函数f
它等效于在window
对象中创建一个属性并将函数定义分配给该变量,如果您创建一个函数:
function myFun() { console.log('my function') };
and then check the value of window.myFun
you'll notice it is the same function as myFun
:然后检查window.myFun
的值,您会注意到它与myFun
功能相同:
window.myFun === myFun // true
You'll also notice that modifying window.myFun
changes/overwrites myFun
.您还会注意到修改window.myFun
更改/覆盖myFun
。
Eg例如
function myFun() { console.log('myFun') }; myFun(); // Prints: 'myFun' // Overwrite myFun window.myFun = function () { console.log('NoFun') }; myFun(); // Prints: 'NoFun'
The second definition of the function takes precedence.函数的第二个定义优先。
I recommend you read the chapter on Functions from JavaScript: the good parts by Crockford.我建议你阅读 JavaScript 中的函数一章:Crockford 的好部分。
函数是内存堆栈中的数据,因此当您定义另一个同名函数时,它会覆盖前一个函数。
Well obviously you're not meant to define the same function twice.很明显,您不打算两次定义相同的函数。 However, when you do, the latter definition is the only 1 that applies.但是,当您这样做时,后一个定义是唯一适用的定义。 Try not to do that.尽量不要那样做。 Find another way other than giving two functions the same name.除了给两个函数同名之外,找到另一种方法。
第二个函数取代了第一个函数,您可以随时通过修改函数名称来更改它,如果不是,您可以添加多个参数..如果需要的话...以及对这种行为的解释,与其他编程语言不同javascript 在执行时不会返回任何错误..所以你可以假设它只是在执行过程中通过覆盖函数来纠正自己。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.