简体   繁体   中英

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. 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. 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:

(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:

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

You'll also notice that modifying window.myFun changes/overwrites 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.

函数是内存堆栈中的数据,因此当您定义另一个同名函数时,它会覆盖前一个函数。

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 在执行时不会返回任何错误..所以你可以假设它只是在执行过程中通过覆盖函数来纠正自己。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM