programing

JavaScript에서 함수 선언

nasanasas 2020. 9. 8. 08:03
반응형

JavaScript에서 함수 선언


중복 가능성 :
자바 스크립트 : var functionName = function () {} vs function functionName () {}

함수를 선언하는이 두 가지 방법의 차이점은 무엇입니까?

function someFunc() { ... }

var someFunc = function() { ... }

나는 기술적 의미에서 묻는 것이 아닙니다. 가독성을 위해 어느 것이 더 나은지, 어떤 스타일이 선호되는지 묻는 것이 아닙니다.


나는 여기에있는 대부분의 사람들과 다른 의견을 가지고 있습니다. 기술적으로이 구문 함수에게 두 가지를 선언 동일한 의미 할 수있다 ( . 나는 그들이 기술적으로 DIFF입니다 왜 사랑하는 게시물에 읽어 내 마지막 문장에 잘못된 서서, 내가 왜 마지막에 추가 할 것입니다 ); 그러나 그들이 진화하는 패턴에서 역할을하는 방식은 엄청납니다. Doughlas Crockford의 "Javascript : The Good Parts"를 강력히 추천합니다.

그러나 미묘하고 단순한 방식으로 나의 요지를 증명하기 위해; 여기에 작은 예가 있습니다.

//Global function existing to serve everyone
function swearOutLoud(swearWord) {
    alert("You "+ swearWord);           
}
//global functions' territory ends here

//here is mr. spongebob. He is very passionate about his objects; but he's a bit rude.
var spongeBob = {
    name : "squarePants",
    swear : function(swearWord) {
                name = "spongy";
                alert("You "+ swearWord);
                return this;
            }
}

//finally spongebob learns good manners too. EVOLUTION!
spongeBob.apologize = function() {
    alert("Hey " + this.name + ", I'm sorry man!");
    return this;
}


//Ask spongebob to swear and then apologize in one go (CASCADING EFFECT!!)
alert(spongeBob.swear("twit").apologize());

위의 코드를 보면 swearOutLoud라는 이름으로 함수를 선언했습니다. 어떤 물건이나 전화에서 욕설을 받아 출력을 제공합니다. 전달 된 "this"매개 변수와 인수를 사용하여 모든 객체에 대해 작업을 수행 할 수 있습니다.

그러나 두 번째 선언은 "spongeBob"이라는 객체의 속성으로 선언됩니다. 이것은 유의해야 할 중요합니다. 여기에서 저는 객체 중심 행동으로 이동하고 있습니다. 또한 반환 할 다른 것이 없으면 "this"를 반환하면서 "계단 효과"를 유지하고 있습니다.

비슷한 일이 jquery에서 수행됩니다. 이 계단식 패턴은 프레임 워크 등을 작성하려는 경우 중요합니다. 빌더 디자인 패턴에도 링크합니다.

But with functions declared as an attributes of an object I am able to achieve an object centric behavior which leads to a better programming paradigm. Unless designed well; individual functions declared outside with global access lead to a non-object oriented way of coding. I somehow prefer the latter.

To see cascading in effect, look at the last statement where you can ask spongebob to swear and apologize at once; even though apologize was added as an attribute later on.

I hope I make my point clear. The difference from a technical perspective may be small; but from design and code evolution perspective it's huge and makes a world of a difference.

But thats just me! Take it or leave it. :)

EDIT:

So both the calls are technically different; because a named declaration is tied to global namespace and is defined at parse time. So can be called even before the function is declared.

 //success
 swearOutLoud("Damn");

function swearOutLoud(swearWord) {
    alert("You " + swearWord)
}

Above code will work properly. But code below will not.

swear("Damn!");
    var swear = function(swearWord) {
    console.log(swearWord);
}

One advantage of using function someFunc() { ... } is that the function name appears in Firebug debugger. Functions that are declared the other way (var someFunc = function() { ... }) come up as anonymous.


Actually, the difference is that the second declaration gives us the ability to declare functions like this making it possible to have a function as a property for an object :

var myObject=new Object();
myObject.someFunc=function() { ... }; 

Style wise the second example is more consistent with other common ways to declare functions and therefore it could be argued that it is more readable

this.someFunc = function() { ... }
...
someFunc: function() { ... },

However, as also mentioned it's anonymous and therefore the name does not appear when profiling. Another way to declare the function is as follows which gets you the best of both worlds

var someFunc = function someFunc() { ... }

Another difference is that, on most browsers, the latter allows you to define different implementations depending on circumstances, while the former won't. Say you wanted cross-browser event subscription. If you tried to define a addEventListenerTo function thusly:

if (document.addEventListener) {
    function addEventListenerTo(target, event, listener) {
        ....
    }
} else if (document.attachEvent) {
    function addEventListenerTo(target, event, listener) {
        ....
    }
} else {
    function addEventListenerTo(target, event, listener) {
        ....
    }
}

on some browsers, all the functions end up being parsed, with the last one taking precedence. Result: the above just doesn't work. Assigning anonymous functions to variables, however, will work. You can also apply functional and basic aspect oriented programming techniques using anonymous functions assigned to variables.

var fib = memoize(function (n) { 
    if (n < 0) return 0;
    if (n < 2) return 1;
    return fib(n-1) + fib(n-2); 
});

...
// patch the $ library function
if (...) {
    $ = around($, fixArg, fixResult);
}

It is both true that the first form:

function test() { }

is a more recognized syntax and that the second form:

var test = function() { ... }

allows you to control the scope of the function (through the use of var; without it, it would be global anyway).

And you can even do both:

var test = function test() { ... test(); ... }

This allows you to define a recursive function in the second form.


For readability, I'd say the first is clearly better. A future maintenance programmer, even assuming they're familiar enough with javascript to know many of the finer points coming up in this thread, are going to assume the first format.

For example, if they should some day want to ctrl-f to search for the definition of your function to see what's happening in there, are they going to first search for someFunc = function() or function someFunc()?

Also, to get downright typographical about it (since we're talking readablity) readers are often scanning the text quickly, and would be more inclined to skip over a line that starts with "var" if they're looking for a function definition.

I know this is a non-technical answer, but it's harder for humans to read code than computers.


When you write

function Test() {
}

JavaScript is really creating a property to which it assigns the function object that once called will execute the code reported in the function definition. The property is attached to the object window, or to the object that contains the function definition.

참고URL : https://stackoverflow.com/questions/1925976/declaring-functions-in-javascript

반응형