본문 바로가기

제이쿼리

jQuery에서 함수를 선언하는 5 가지 다른 방법

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

소개

JavaScript / jQuery를 사용하여 함수를 선언하는 몇 가지 다른 방법이 있기 때문에 JavaScript 함수를 선언하는 방법을 선택하는 것은 초보자에게는 혼란 스러울 수 있습니다. 나는 각자의 이점과, 당신이 멋진 jQuery 코드를 작성할 때 어떻게 그리고 왜 사용하는지에 대해 설명하려고 노력할 것이다.

 

 

1. 기본 JavaScript 함수

이것은 JavaScript에서 함수를 선언하는 가장 간단한 방법입니다. 예를 들어, 곱셈 (x, y)라는 간단한 함수를 쓰고 싶습니다.이 함수는 두 개의 매개 변수 x와 y를 취하고, 간단한 x 배 y를 수행하여 값을 반환합니다. 다음과 같이 정확하게 수행 할 수있는 몇 가지 방법이 있습니다.

 

function multiply(x,y) {

     return (x * y);

}

console.log(multiply(2,2));

//output: 4

당신이 뭔가를 테스트하는 빠른 기능을 원한다면 어쩌면 이것이 유일한 기회 일 것입니다. 좋은 코딩이 아니며 코드 재사용을 촉진하지 않습니다.

 

2. 가져 오기 / 설정을위한 JavaScript 함수

모델 값을 가져오고 / 설정 / 삭제하기위한 전용 유틸리티가 필요한 경우 함수를 이와 같은 변수로 선언 할 수 있습니다. 이것은 함수에 의해 계산 된 선언에 변수를 할당 할 때 유용 할 수 있습니다.

 

var multiply = function(x,y) {

     return (x * y);

}

console.log(multiply(2,2));

//output: 4

 

//The same function but with a self execution to set the value of the variable:

var multiply = function(x,y) {

     return (x * y);

}(2,2);

console.log(multiply);

//output: 4

3. 자신의 jQuery 함수 만들기

이것은 DOM 요소에서 일반 jQuery 함수처럼 사용할 수있는 함수를 선언하는 멋진 방법입니다! Rememeber jQuery.fn은 jQuery.prototype의 별칭입니다. jQuery.fn.init.prototype = jQuery.fn = $ .fn을 코딩 할 때 시간을 절약 할 수 있습니다.

 

jQuery.fn.extend({

    zigzag: function () {

        var text = $(this).text();

        var zigzagText = '';

        var toggle = true//lower/uppper toggle

            $.each(text, function(i, nome) {

                zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();

                toggle = (toggle) ? false : true;

            });

    return zigzagText;

    }

});

 

console.log($('#tagline').zigzag());

//output: #1 jQuErY BlOg fOr yOuR DaIlY NeWs, PlUgInS, tUtS/TiPs & cOdE SnIpPeTs.

 

//chained example

console.log($('#tagline').zigzag().toLowerCase());

//output: #1 jquery blog for your daily news, plugins, tuts/tips & code snippets.

jQuery 함수를 함께 연결할 수 있도록 요소를 반환하는 것을 잊지 마십시오.

 

4. 기존 jQuery 함수 확장하기

(또는 추가 기능을 사용하여 기존 jQuery 함수를 확장하거나 jQuery 네임 스페이스를 사용하여 호출 할 수있는 자신 만의 함수를 만드는 방법 (일반적으로 $ 기호를 사용하여 jQuery 네임 스페이스를 나타냄)이 예제에서 $ .fn.each 함수에는 사용자 지정 동작으로 수정되었습니다.

 

(function($){

 

// maintain a to the existing function

var oldEachFn = $.fn.each;

 

$.fn.each = function() {

 

    // original behavior - use function.apply to preserve context

    var ret = oldEachFn.apply(this, arguments);

    

    // add custom behaviour

    try {

        // change background colour

        $(this).css({'background-color':'orange'});

        

        // add a message

        var msg = 'Danger high voltage!';

        $(this).prepend(msg);

    }

    catch(e) 

    {

        console.log(e);

    }

    

    // preserve return value (probably the jQuery object...)

    return ret;

}

 

// run the $.fn.each function as normal

$('p').each(function(i,v)

{

    console.log(i,v);

});

//output: all paragrahs on page now appear with orange background and high voltage!

 

})(jQuery);

5. 사용자 정의 네임 스페이스의 함수

사용자 정의 네임 스페이스 에서 작성 기능 을 사용하려면 이러한 방식으로 선언해야합니다. 마지막 함수를 제외한 쉼표를 추가하는 데 필요한 네임 스페이스에 추가 함수를 추가 할 수 있습니다. 네임 스페이스에 대해 확신이 서지 않은 경우 jQuery 함수 네임 스페이스를 일반 영어로 보시기 바랍니다.

 

JQUERY4U = {

    multiply: function(x,y) {

        return (x * y);

    }

}

//function call

JQUERY4U.multiply(2,2);

Colored by Color Scripter

cs