Sneak in and briefly introduce anonymous and closure functions and object-oriented programming in JavaScript. Let's start with a brief introduction to the secret name function in JavaScript.
In JavaScript, functions are defined in the following 3 ways:
1. The most common way to define:
function functionval (variable) { return variable;}
View Code
2. Using the function constructor, use the parameter and function body contents as String parameters [not recommended]:
var objfunction=New Function (' variable ', ' return 3*variable ');
View Code
3.3rd Definition of the way
var functionval=function(variable) { return variable;}
View Code
The 3rd Method "=" On the right is an anonymous function that assigns the function object to the variable to the left of "=" after the definition is complete.
The above mentioned anonymous function, next familiar with the role of anonymous functions:
The most important function of an anonymous function is the ability to create closures and namespaces, and the two main features of an anonymous function determine the ability to use function to implement JavaScript object-oriented programming, as shown in the following code, which demonstrates how to implement private and shared members using anonymous functions:
(function($){ varPrivateval= ' This is a global private static variable '; /// ///Global Private Menthod /// functionprivatefunction (Varibale) {alert (' This is a global private function ')} $.namespace=function() {alert (' This is a new name space '); }; $.namespace.publicfunction (variable) {alert (' This was a public function '); }} (JQuery))
View Code
One way to use JavaScript that is similar to the anonymous function definition above is as follows:
$ (function() { alert (' A new method call document Ready function ');})
View Code
This method is equivalent to:
$ (document). Ready (function () { alert (' A method call document Ready function ');})
View Code
A brief introduction to JavaScript anonymous functions and object-oriented programming