I saw three different function definitions in jQuery. What is the correct way to use them?
Example 1:
function example() {
// code here
}
Example 2:
jQuery('#Example').click(function() {
// code here
});
Example 3:
var example = {
demo : function() {
// code here
}
}
Why should I choose which?
-
It depends on what you are doing. What do you want to achieve?edkeveked– edkeveked2017年11月20日 22:11:26 +00:00Commented Nov 20, 2017 at 22:11
-
1why do not they all do the same thing?Özgür Can Karagöz– Özgür Can Karagöz2017年11月20日 22:12:37 +00:00Commented Nov 20, 2017 at 22:12
3 Answers 3
There is no 'best' here, as each function definition is separate and serves different purposes. Also note that only the second example has anything to do with jQuery.
Your first example is just a vanilla JS function definition, nothing special about this.
Your second is a jQuery click event handler which is used to declare logic which should be executed when the click event occurs on the selected element.
The third example is a function definition inside an object, which can be useful when using an OOP approach (as if to declare a class/model), or just passing a collection of values around in your logic.
Comments
Example 1 and 3 have nothing to do with jQuery. These are vanilla javascript snippets.
On example 2, it's recommended to use this syntax instead :
jQuery('#example_container').on('click', '#Example', function(event) {
// code here
});
This lets you delegate the event handling, which means even if you created that element after the page was loaded, the event will still be handled.
4 Comments
it's recommended to use this syntax instead... it's only recommended if dealing with dynamically appended elements. There's nothing inherently wrong with using a static event handler.Your first example:
function example() {
// code here
}
Is the way to define a function and it is going to be available depending on its scope.
The second example:
jQuery('#Example').click(function() {
// code here
});
You are not only defining a Function but you are adding this function into the click event for a html element that has the id "Example"
The third Example:
var example = {
demo : function() {
// code here
}
}
You are defining a function inside an Object. So this function is going to be the method "demo" of the object "example" you just created.