简体   繁体   中英

Best way to define and call functions in Javascript

Below is just some sample Javascript that I posted that shows 2 different ways that javascript functions are being defined and called.

Is there a name for these different methods?

Which method is preferred?

The first code block looks really simple, pretty much the same as a procedural PHP function is defined and called.

The second I realize is set up more like a class/namespace it just get's a little confusing for me as I have not studied javascript too much yet. Am I correct in my thinking that all these functions could be coded in either method as the first or second code blocks and still work?

Sorry if my question is not clear enough, I will revise if needed, thanks for the help/info

initCommentsHelp();

function initCommentsHelp() {
    $('#view-comments-help-a').live('click', function() {
      $('#comments-help').slideToggle("normal");
      return false;
    });
}

VS doing this

Screenshot.Like.Shot.toggle();
Screenshot.Comment.toggle();
Screenshot.Flag.flag();
Screenshot.Flag.unflag();

var Screenshot = {
    Like: {
        Shot: {
            toggle: function() {
                if ($('.fav a.fav-toggle.processing').length == 0) {
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data: data,
                        beforeSend: function() {
                            $('.fav-toggle').addClass('processing');
                            $link.text('Wait...');
                        },
                        success: function(responseHtml) {
                            $('#like-section').replaceWith(responseHtml);
                        }
                    });
                }

                return false;
            }
        },
    Comment: {
                toggle: function() {
                    var link = $(this);
                    var data = link.hasClass('liked-by-current-user') ? {_method: 'delete'} : null;
                    $.ajax({
                        type: 'POST',
                        url: this.href,
                        data: data,
                        success: function(responseHtml) {
                            link.closest('.comment').replaceWith(responseHtml);
                        }
                    });

                    return false;
            }
        }
    },
    Flag: {
        // Flag a screenshot as inappropriate or Appropriate
        flag: function(){
            var link = $(this);
            var screenshotId = link.modelId();
            if(!confirm("Are you sure you want to flag this shot?"))
                return false;

            $.ajax({
                type: 'POST',
                url: this.href,
                data: {
                    screenshot_id: screenshotId
                },
                success: function(responseHtml) {
                    $('#flag-section').html(responseHtml);
                }
            });

            return false;
        },
        unflag: function() {
            var link = $(this);
            var screenshotId = link.modelId();
            $.ajax({
                type: 'POST',
                url: this.href,
                data: {
                    _method: 'delete',
                    screenshot_id: screenshotId
                },
                success: function(responseHtml) {
                    $('#flag-section').html(responseHtml);
                }
            });

            return false;
        }
    },
};

The first way is generally preferred for writing standalone functions. You can write them as

function testFunction() {
  // your code here...
}

or

var testFunction = function() {
  // your code here...
}

The second example you have posted is used for namespacing your objects. You can read more about namespacing in this article : Namespacing in JavaScript

A function that's an object property (called via an object reference, eg obj.func() ) is what's called a "method". A function not associated with an object is called a "free function". Methods have special access privileges not afforded to free functions. Exactly what those privileges are depends on the language, but all OO languages include a special variable (you can consider it a hidden parameter) available within the function body to access the object the method is bound to. In JS, the name of this parameter is this .

this exists in free functions, where it refers to the global object. You can think of free functions and global variables as being properties of a global, default object. For browsers, the global object is window . Free functions, then, are similar to global variables, which are generally bad . Free functions don't as often cause problems as global variables, but they still can, and for the same reasons. As a result, some developers use objects as namespaces to prevent name collisions.

For example, one module might create a sign function that returns whether a number is positive, negative or 0. Another module might have a sign function that digitally signs a message. These modules are created by different companies, each unaware of the other. Imagine a developer wants to use both modules. If both were defined as free functions, whichever were defined second would replace the first, wreaking havoc in the other module. To prevent this, each function can be defined as properties of separate objects.

The actual difference between free functions and methods is in how they are accessed. Methods are accessed as a property of an object, while free functions are accessed directly by name or as a variable. Note that the same function can be treated as a method or free function, depending on how you access it.

var obj = {
    type: 'method',
    meth: function (){
        return this.type;
    }
};
var func = obj.meth,
    name = 'free';

// the following two lines call the same function, though `this` will be bound differently for each.
obj.meth(); // returns 'method'
func();     // returns 'free'

You can even take a free function and call it as a method in a number of ways:

function func(a, b) {
    return this.foo+a+b;
}
var obj = {foo: 'bar'};
// call func as a method using the `call` method
func.call(obj, 'baz', 'bam');
// call func as a method using the `apply` method
func.apply(obj, ['baz', 'bam']);

// call func as a method in the usual way
obj.meth = func;
obj.meth(1, 2); // 'foo12'

If you look more closely at your second sample, you'll note that most of the methods use the this variable. These must remain methods; making them free functions will likely cause bugs.

One is defining the functions in an object and the other is just defining a function by itself. Functions are first class objects in JavaScript so they don't need an object to be defined.

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