To ensure readability, paper, rather than literal translation, and a lot of example code modification.
1, immediately execute the function
Immediately execute the function, namely Immediately Invoked Function Expression (IIFE), as its name, is at the same time create the function executed immediately. It does not bind any event, there is no need to wait for any asynchronous operation:
(function() { // Code // ... })();
function () {...} is an anonymous function, a pair of brackets surrounding it converts it to an expression, a pair of brackets immediately following the call to this function. Immediately execute the function can also be understood as immediately call an anonymous function. Immediate implementation of the most common scenario is a function: var scope will be limited to a variable within your function, to avoid naming conflicts.
2, closure
For the closure (closure), when the external function returns, the function can still access the internal function of the external variables.
function f1() { var N = 0; // N local variable f1 is a function of function f2 () // f2 function is an internal function f1 is the closure { N + = 1; // use the internal function f2 f1 external function of the variable N console.log(N); } return f2; } was Result = f1 (); result (); // Output 1 result (); // Output 2 result (); // Output 3
Code, the external function f1 is performed only once, the variable N is set to 0, and the internal function f2 assigned to the variable result. Since the external function f1 has been executed, its internal variable N should be cleared in memory, however, is not the case: when the result every time we call, the variable N has been found in memory, and cumulative. why? This is the magic of the closure!
3, the closure defined using private variables
Typically, JavaScript developers use an underscore as a prefix private variables. But in fact, these variables can still be accessed and modified, is not a true private variables. In this case, use a closure to define a real private variables:
function Product() { var name; this.setName = function(value) { name = value; }; this.getName = function() { return name; }; } var p = new Product(); p.setName("Fundebug"); console.log (p.name); // output undefined console.log (p.getName ()); // output Fundebug
Code, the name attribute of the object p is private property, use p.name not directly accessible.
4、prototype
Each constructor has a JavaScript prototype property, properties and methods for setting all instances of objects need to be shared. not include prototype property. JavaScript is supported only inherit the properties and methods through the prototype property.
function Rectangle(x, y) { this._length = x; this._breadth = y; } Rectangle.prototype.getDimensions = function() { return { length: this._length, breadth: this._breadth }; }; var x = new Rectangle(3, 4); var y = new Rectangle (4, 3); console.log(x.getDimensions()); // { length: 3, breadth: 4 } console.log(y.getDimensions()); // { length: 4, breadth: 3 }
Codes, x and y are the constructor function Rectangle object instance is created, they inherit the methods getDimensions prototype.
5, modular
JavaScript is not modular programming language, at least ES6 before landing not. However, for a complex Web applications, modular programming is a basic requirement. In this case, you can use the function to be executed immediately modular, as many JS libraries such as jQuery and we are so Fundebug achieved.
var module = (function() { there are N = 5; function print(x) { console.log("The result is: " + x); } function add(a) { var x = a + N; print(x); } return { description: "This is description", add: add }; })(); console.log(module.description); // 输出"this is description" module.add(5); // 输出“The result is: 10”
The so-called modular, accessibility is based on the need to control the properties and methods of the module, i.e., private or public. In the code, module is a separate module, N for private attributes, print its private methods, decription for public properties, add its sharing method.
6, variable lift
JavaScript will declare all variables and functions moved to the top of its scope, which is called the variable lift (Hoisting). In other words, whether you declare variables and functions in any place, the interpreter will move them to the front of the scope. Therefore, we can first use variables and functions, then declare them.
However, only the variable declaration was promoted, and variable assignment will not be promoted. If you do not get it, sometimes an error occurs:
console.log(y); // 输出undefined y = 2; // initializes y
The above code is equivalent to the following code:
var y; // declare y console.log(y); // 输出undefined y = 2; // initializes y
In order to avoid BUG, developers should declare variables and functions at the start of each scope.
7, currying
Curried, that Currying, may be a function become more flexible. We can call it a one-time pass more parameters; only some of the parameters can be passed to call it, it returns a function to handle the rest of the parameters.
var add = function(x) { return function(y) { return x + y; }; }; console.log (add (1) (1)); // Output 2 var add1 = add (1); console.log (add1 (1)); // Output 2 was ADD10 = add (10); console.log (add10 (1)); // Output 11
Code, we can get a one-time pass add1 and add10 function after 2 1 as an argument add (1) (1), can also pass a parameter, so very flexible.
8, apply, call bind method
JavaScript developers need to understand the different points apply, call the bind method. They have in common is the first parameter is this, i.e., the function is dependent on the context.
Of the three, call the method is the simplest, it is equivalent to the value specified call this function:
was user = { name: "Rahul Mhatre", whatIsYourName: function() { console.log(this.name); } }; user.whatIsYourName(); // 输出"Rahul Mhatre", was user2 = { name: "Neha Sampat" }; user.whatIsYourName.call(user2); // 输出"Neha Sampat"
The method is similar to apply call method. The only difference is two, the method using an array Apply the specified parameters, and a separate call for each parameter to specify a method:
-
apply(thisArg, [argsArray])
-
call(thisArg, arg1, arg2, …)
was user = { greet: "Hello!", greetUser: function(userName) { console.log(this.greet + " " + userName); } }; was greet1 = { greet: "Hola" }; user.greetUser.call(greet1, "Rahul"); // 输出"Hola Rahul" user.greetUser.apply(greet1, ["Rahul"]); // 输出"Hola Rahul"
The method of using the bind, may bind as a function of this value, then returned as a new function:
was user = { greet: "Hello!", greetUser: function(userName) { console.log(this.greet + " " + userName); } }; var greetHola = user.greetUser.bind({greet: "Hola"}); var greetBonjour = user.greetUser.bind({greet: "Bonjour"}); greetHola("Rahul") // 输出"Hola Rahul" greetBonjour("Rahul") // 输出"Bonjour Rahul"
9、Memoization
Memoization for calculating the optimized time-consuming, the buffer memory by the calculation result, so that for the same input values, only the next memory read result.
function memoizeFunction(func) { var cache = {}; return function() { var key = arguments[0]; if (cache[key]) { return cache[key]; } else { var val = func.apply(this, arguments); cache [key] = val; return val; } }; } var fibonacci = memoizeFunction(function(n) { return (n === 0 || n === 1) ? n : fibonacci(n - 1) + fibonacci(n - 2); }); console.log (fibonacci (100)); // output 354224848179262000000 console.log (fibonacci (100)); // output 354224848179262000000
Code, 2nd calculated fibonacci (100) only need to read the result directly in memory.
10, function overloading
The so-called function overloading (method overloading), is a function of the same name, but not the same input and output. Or, a function to allow a variety of different inputs depending on input, and returns the result. Intuitively, function overloading can be achieved by switch or else if ..., which leave it up. The father of John Resig jQuery presents a very clever (Bian) Miao (TAI) method using closures.
In effect, find methods people objects allows three different inputs: 0 arguments, return all names; when a parameter to find names according firstName and return; 2 parameters, to find names in accordance with the full name and return.
The difficulty is, people.find can only bind a function, and that it why can handle three different input it? At the same time it can not bind the three functions find0, find1 and find2 ah! The key here is that the old property.
From the calling sequence addMethod function, people.find final binding is find2 function. However, when binding find2, old is find1; Similarly, when binding find1, old functions as find0.3 find0, find1 find2 and so linked by a closure.
According to addMethod logic, when f.length and arguments.length does not match, it will go call the old, until the match.
function addMethod(object, name, f) { var old = object[name]; object[name] = function() { // f.length number of parameters defined as a function of time // arguments.length is the number of parameters of the function call if (f.length === arguments.length) { return f.apply(this, arguments); } else if (typeof old === "function") { return old.apply(this, arguments); } }; } When // does not pass parameters, return all the name function find0() { return this.names; } When // pass a parameter and returns the matching name firstName function find1(firstName) { were result = []; for (var i = 0; i < this.names.length; i++) { if (this.names[i].indexOf(firstName) === 0) { result.push(this.names[i]); } } return result; } When // pass two parameters, return firstName and lastName match the name function find2(firstName, lastName) { were result = []; for (var i = 0; i < this.names.length; i++) { if (this.names[i] === (firstName + " " + lastName)) { result.push(this.names[i]); } } return result; } var people = { names: ["Dean Edwards", "Alex Russell", "Dean Tom"] }; addMethod(people, "find", find0); addMethod(people, "find", find1); addMethod(people, "find", find2); console.log(people.find()); // 输出["Dean Edwards", "Alex Russell", "Dean Tom"] console.log(people.find("Dean")); // 输出["Dean Edwards", "Dean Tom"] console.log(people.find("Dean", "Edwards")); // 输出["Dean Edwards"]
Bi-mao wonderful classroom courses recommended:
1.Cloudera data analysis courses;
2.Spark Hadoop development and training;
3. Big Data machine learning recommendation systems;
4.Python data analysis and machine learning practical;
Click here to add a caption
For more details, please look at our public number: Bi Mao data - Course Products - Bi-mao classroom
Register now interactive learning was massive currency, a large number of quality courses free delivery!