JavaScript에서 괄호로 함수를 호출하면 차이가 있습니까?
빈 괄호가 있거나 괄호가 전혀없는 함수를 호출 할 때 차이를 발견했습니다. 그러나 함수에 인수를 전달하지 않으므로 다음과 같은 차이점이 무엇인지 궁금했습니다.
window.onload = initAll();
과
window.onload = initAll;
그이면의 원리를 설명 해주세요.
window.onload = initAll();
이것은 즉시 실행 되고 함수의 반환 값 을에 할당합니다 . 이것은 일반적으로 원하는 것이 아닙니다 . 이해하기 위해서는 함수를 반환해야합니다.initAll()
window.onload
initAll()
window.onload = initAll;
이것은 실제 함수 를 할당합니다. window.onload
JavaScript에서 @Felix가 말했듯이 함수는 실행하지 않고도 일류 객체이기 때문에 가능합니다. initAll
로드 이벤트에 의해 실행됩니다.
Pekka의 말은 맞지만 함수 포인터 나 델리게이트를 완전히 이해하지 못하는 사람에게 설명하는 데 도움이되는 예를 들어 조금 더 자세히 설명하고 싶습니다.
window.onload
설명하기 위해 약간 고안 되었기 때문에 사용하지 않을 것 입니다. 대신 간단한 곱하기 함수를 사용하여 데모합니다.
function Multiply(operator, operand) {
return operator * operand;
}
다음과 같이 작성할 수 있습니다.
Multiply = function(operator, operand) {
return operator * operand;
}
첫 번째 예에서는 그 의미가 명확하지 않을 수 있지만 두 번째 예에서는라는 변수에 2 개의 매개 변수가있는 함수를 할당하고 있음을 더 명확하게 보여줍니다. Multiply
이러한 함수의 할당 개념은 JavaScript 전체에서 공통적입니다. 이것은 함수가 "일급 시민" 이라는 사실을 보여주는 작은 데모입니다. 즉 , 마치 값을 전달하는 것처럼 정확하게 전달 될 수 있습니다.
이제 할당의 차이를 살펴 보겠습니다.
var operator = 3;
var operand = 4;
var ret = Multiply(operator, operand);
ret 변수를 정의하는 시점에서 Multiply
실행되고 반환 값이 할당됩니다.- ret
12가됩니다.
다른 방법으로 다시 시도해 보겠습니다.
var operator = 3;
var operand = 4;
var ret = Multiply;
이제 정의의 시점에서 ret
, ret
당신이됩니다 Multiply
당신의에서 얻은 결과 인 반대 기능을 Multiply
작동합니다. 를 호출 ret()
하면 Multiply
함수가 실행되며 호출 한 것처럼 정확하게 호출 할 수 있습니다 Multiply(operator, operand)
.
var out = ret(3, 4);
와 같다
var out = Multiply(3, 4);
ret
의 대리인 으로 사용할 것이라고 효과적으로 말씀하셨습니다 Multiply()
. 를 호출 할 때 ret
우리는 실제로 Multiply
함수를 참조 합니다.
당신의 위로 window.onload
. 이것을 다음과 같이 생각하십시오.
window.onload = function() {
//Doing what all good window.onload functions should do...
}
initAll = function() {
return 12;
}
So as you can see, window.onload
is a function just like any other function, there's nothing special about it. You can assign it a value, assign it a function, null it out if you wish - the point is that there's nothing any more special about window.onload
than there is about your own function. The only slightly different thing is that it gets called by the window when it's loaded. [Disclaimer: I've never actually nulled out window functions, so I'm not sure if this will cause negative repercussions. One would hope they check to see if a function is assigned before calling it i.e. if (window.onload) window.onload();
].
Now calling initAll()
what we're saying is:
window.onload = initAll();
which might as well say:
window.onload = 12;
But when we say initAll
without the parentheses, what we're really saying is: I want to replace whatever my window.onload function is, with a new function - i.e. I want to replace it with my initAll
function, so that any calls to window.onload
runs my initAll
code.
So:
window.onload = function() {
//Doing what all good window.onload functions should do...
}
is replaced with:
window.onload = function() {
return 12;
}
So any call to window.onload
will execute your initAll
function instead of whatever window.onload
was originally. You have replaced the original function with your new function.
In fact, you could equally write:
window.onload = function() {
//Write all your init code right in here instead of having a separate
//initAll function.
}
Another example that may demonstrate better is this:
var d = new Date();
var currentTime = d.getTime();
Whatever the time was at the time d
is defined ends up assigned to currentTime
. Great, but that's only useful if we want to find out what time the function containing that code was called - i.e. at page load time. What if we want the current time any time that currentTime
is called?
var currentTime = function() {
var d = new Date();
return d.getTime();
}
var a = currentTime(); //The current time at the point a is defined...
var b = currentTime; //b is a functional reference to currentTime...
var c = b(); //The current time when variable c is defined
var d = c; //The current time when variable c was defined
Notice how we call b()
in our c
and d
assignments exactly as we could call currentTime()
?
Functions in javascript are first-class citizens, and as such, can be assigned to other variables or passed around as arguments.
So, when you do
window.onload = initAll;
You are setting the onload
property of the window
object to reference the initAll
function itself.
When you do
window.onload = initAll();
You are setting the onload
property to hold the return value of initAll, since it will execute in place on that line.
initAll
is a reference to a function value and the brackets operator appended to the function name RUNS this function object.
So if you do something like
a = initAll
then a
will become the same as initAll
- for example you can do a()
- but with
a = initAll()
the variable a
will get the return value of the executed initAll
function
I'm 6 years late but I feel this could have been explained a lot simpler than the above answers.
So here is the TLDR; or bird's eye view when calling functions using and not using ()
's
Lets take this function for example:
function foo(){
return 123;
}
if you log "foo" - without ()
console.log(foo);
---outout------
function foo(){
return 123;
}
Using no ()
means to fetch the function itself. You would do this if you want it to be passed along as a callback.
if you log "foo()" - with ()
console.log(foo());
-----output-----
123
Using ()
after a function means to execute the function and return it's value.
'Programing' 카테고리의 다른 글
기본적으로 tinymce 붙여 넣기를 일반 텍스트로 만드는 방법 (0) | 2020.08.19 |
---|---|
Android의 RadioButton에 OnClickListener를 설정하는 방법은 무엇입니까? (0) | 2020.08.19 |
이벤트를 한 번만 바인딩 (0) | 2020.08.19 |
.animate () 콜백이 두 번 호출됩니다. (0) | 2020.08.19 |
HTML5 입력 유형 범위 표시 범위 값 (0) | 2020.08.19 |