JS advanced
1. Object-oriented
Three characteristics of object-oriented: encapsulation, inheritance and polymorphism;
tips:JS has no polymorphism;
2. Packaging function
Traditional ways of encapsulating functions:
function fun_1(){
}
The problems of encapsulation function are as follows: 1. Global variable contamination;
2. The code structure is chaotic, which is not conducive to maintenance.
Constructor:
function Person(){
this.name = name;
this.age = age;
this.sayHi = function (){};
}
var p = new Person;
var p1 = new Person;
tips: Here, if you put the method inside the constructor,
Every time a constructor is used to create an object, a new space is needed to save the method.
And these methods are the same, which results in the waste of resources.
tips: So we put all the methods we need to create objects in prototype.
Each instantiated object created with this constructor points to the same prototype.
tips: If the constructor does not return, it calls undefined.
eg:
var pig = new Pig(); - This creates an instantiated object named pig;
var pig2 = Pig(); - In this way, only the constructor is called as a function, and the return value of the function is assigned to pig2;
prototype:
1. Constructor. Prototype can access the prototype.
2. The instantiated object created. _proto_ can access the prototype;
3. The prototype can also access the prototype's constructor using the. constructor method.
4. Instantiation. Constructor can access the constructor, but the constructor cannot access the instantiated object.
5. In the prototype, the common method of instantiating objects is stored.
The constructor stores the operation of initializing the attributes of newly created objects.
tips: try to write all the functions in the prototype function to facilitate the use of instantiated objects;
In the constructor, only the necessary functions are invoked, and the functions in the prototype function can be classified. In the constructor, only the general functions are performed, and the fine classes are encapsulated in the prototype.
6. If each newly created object calls its method, it will first find the method from its own properties.
If there is no such method in the properties of the instantiated object, it will be found in its prototype.
7. When the prototype of the constructor is replaced by another object in the middle, the prototype of the object that has been created will not change.
But after that, the prototype of the object created will point to the replaced object.
8. Using the dynamic characteristics of the object, we can add members to the prototype object.
eg:
Person.prototype.name = "xxx";
Person.prototype["name"] = "xxx";
tips: both methods are applicable;
tips: The attributes and methods of an object are collectively called members.
3. Final version of prototype
4, inheritance
(1) Mixed Inheritance
The attribute of object 1 is assigned to object 2 by using for-in loop.
eg:
for(var key in obj_1){
obj_2[key] = obj_1[key];
}
tips: Inheritance can only be achieved for a single object through mixed inheritance.
To make all created objects have the attributes of an object, it would be very troublesome to use the hybrid method.
(2) prototype inheritance
There are two ways to make the prototype of the constructor have the properties of an object:
1. Specify the prototype of the constructor as the object directly.
2. The attributes of the object are added to the prototype iteratively, and this method is recommended.
(3) Succession of Classics
var obj_2 = Object.create(obj_1);
Create an obj_2 and make obj_1 the prototype of obj.
(4) Application: Safe use of built-in objects
If all the methods needed are placed in the prototype, the structure of the prototype will become chaotic.
And everyone puts the method in the prototype, and multi-person operation will cause method conflict.
So we need to add new prototype inheritance to make it safe to use built-in objects.
eg:
var arr = new MyArray();
MyArray.prototype = [];
tips: This inserts a custom prototype MyArray between arr and the built-in object Array.
We can store the methods we need in a custom prototype so that the array objects created can still get the methods from the built-in object Array.
5. Object.prototype members
(1) hasOwnProperty("attribute name");
eg:
obj.hasOwnProperty(key);
Determine whether the attribute key exists in the obj object.
(2),isPrototypeOf
eg:
obj_1.isPrototypeOf(obj_2);
Determine whether obj_1 is the prototype of obj_2;
(3),propertyIsEnumerable
eg:
obj.propertyIsEnumerable("attribute name");
Determine whether the attribute can be obtained by enumeration in obj.
tips: This attribute must be owned by the object itself, not referenced from prototype;
(4),toString()
toLocaleString()
Both are methods for converting strings, and LocalString is displayed in locally related formats.
tips: A very obvious difference is the date displayed by the Date object.
(5),valueOf()
array.valueOf() is still an array;
object.valueOf() is still an object;
6. function members
(1) length: the number of formal parameters of a function
(2),name
The name of the anonymous function is anonymous.
(3),prototype:
When a function exists as a constructor, prototype points to the prototype of the constructor.
(4),caller
Where a function is called internally, the caller points to the external function.
If it's called globally, it's null.
eg:
function Person(a, b){
console.log(Person.caller);
}
function f1(){
Person(1,2,3);
}
f1();
(5),__proto__:
When a function exists as an instantiated object, _proto_ points to the prototype of the instantiated object.
7. Function object
(1),
var fn1 = new Function(arg1, arg2, arg3, ..., argN, body);
body Write the code inside the function. arg1 Refers to the formal parameters of the function.
//At this point, a function named fn1 is created.
eg:
var func = new Function(){"num", "console.log(num);"};
tips:Function It is a constructor, which can be considered as either a constructor or a constructor. Function(Namely oneself)Instance object;
//The constructor of any function is Function.
(2),instance of
//To determine whether the prototype of the constructor is on the prototype chain of the object, the return value is true or false.
eg:
obj instanceof Object; //obj is an instantiated object or constructor
tips: Any object instanceof Object,The return values are true;
(3),Three Ways to Create Functions
eg:
var fn = new Function();
var fn = function (){};
function fn(){}
tips:Functions are called with parentheses, and assignments without parentheses.
8. eval function
(1) Evaluate, parse the string into js code;
eg:
eval("var a = 10;");
After using the eval method, this string will create a variable a with an assignment of 10.
(2) Converting strings in JSON format to js objects
1. JSON.parse(json) string, the return value is js object, there are compatibility problems;
2. json2.js plug-in, which can be solved by introducing the plug-in;
3. Use eval function to convert JSON format strings into objects.
tips: code blocks can be partitioned using {} to make the code structure clearer;
eg:
{
var a = 10;
}
When using the eval method, in order to avoid the {} at the beginning and end of the json string being parsed into code blocks,
eg:
Var obj = Eval ("("+JSON string +");
or
eval("var obj = " + str);
Tips: Both Function and eval can convert strings into code, but this is not recommended.
This approach has security issues (such as XSS cross-site scripting attacks);
9. Static and instance members
(1) Static members: members accessed by constructors, that is, members provided by constructors when new;
(2) Instance Members: Members accessed by an instance, that is, the attributes of the instance itself;
10. arguments object
The arguments object stores all the arguments inside the incoming function.
Properties:
(1) length, which can indicate the number of arguments passed in;
(2) callee, which represents the function where the current arguments object is located;
eg:
function test(a, b){
console.log(arguments.callee);
}
test(1, "a");
tips: The content of the text() function is displayed on the console at this time.
11, recursion
The function itself calls itself, that is, recursion.
(1) Two Conditions of Recursion
1. Call oneself inside the function;
2. The function has an end condition, and it ends recursively when the end condition reaches.
tips: Recursion must have an end condition. Recursion without an end condition is a dead cycle.
(2) Recursion is very inefficient and resource-intensive, which should be used in conjunction with caching.
(3),eg:
Find the sum of the first n terms:
function sum(n){
if(n == 1){
return 1;
}
return sum(n - 1) + n;
}
tips: when the minimum value occurs, i.e. n==1, the end condition achieves the value that needs to be return ed;
1+2+3+4
1+2+3
1+2
1
So when n = 1, return 1.
Find the factorial of n:
function fct(n){
if(n == 1){
return 1;
}
return fct(n - 1) * n;
}
tips: 1*2*3*4*5
1*2*3*4
1*2*3
1*2
1
So when n = 1, return 1;
12. Scope and Variable Improvement
(1),stay js There are and only functions that can create scopes.
//The function corresponding to the lexical scope is called the dynamic scope.
js Its scope is lexical scope.
js Not dynamic scope;
tips: If it is a dynamic scope, it will take into account the calling environment of the function to judge its variable elevation.
(2),js Implementation is divided into two stages
1,Pre-analysis, variable promotion( hoisting),function and var Promotion;
2,Code execution phase;
tips:stay if Intra-statement var Variables are raised, but assignment operations are not.
eg:
function test(a){
console.log(typeof a);
var a = 123;
}
test(123);
tips:In a function, the argument passed in will do one inside the function. var Formal parameter = Operations of arguments precede all function codes.
//Here, the function is called, and the argument is passed in. The order of execution is:
test(123);
var a = 123;
var a ;
console.log(typeof a);
a = 123;
(3),stay function If the variables that appear in the function are not declared within the function, then they are assigned by searching for the defined variables in the scope of the upper level.
//By analogy, until the var of the variable is found and the global scope is still defined, an error is reported.
tips: if(undefined),by false;
if(0),by false;
if(null),by false;
if(" "),by false;
tips: Attributes in elements can be invoked directly by point method.
//For example, body.id, body.class.
13. Scope Chain and Variable Search Principle
(1) The steps of drawing scoping chains:
1. Looking at the whole situation, it is a chain, i.e. a top-level chain, marked as a 0-level chain.
2. Look at the global scope, what variables and function declarations are drawn to level 0 in the form of a grid.
3. Find a function again, only the function can restrict the scope, so a new chain is introduced from the function, marked as a first-order chain.
4. Then repeat the previous behavior in each level 1 chain.
(2) Access rules for variables
1. First, look at the chain in which variables are defined and assigned, and if they are used directly.
2. If there is no search on the upper level chain (n - 1 level chain), if there is direct use, stop searching.
3. If you haven't looked up again just now... until the global chain (level 0), you haven't defined it yet.
tips: Note that chains of the same level cannot be mixed lookup
(3),
Foo.get, which means the get attribute in the constructor Foo is called;
Foo().get, which first executes the Foo() function and calls the get attribute of its return value;
tips: Functions are called when parentheses are added.
tips: If the constructor is called as a normal function, its internal this is window.
What is return? No return returns undefined.
new Foo.getName();
Calculate the value of the Foo.getName attribute directly.
new Foo().getName();
new Foo(), which creates an instantiated Foo object, calls its getName method in the object, and looks up the prototype if the object does not have the method itself.
new new Foo().getName();
Similar to the previous example;
tips: new and one (), the middle part is the constructor, and new itself does not affect the results;
14, closure
(1) Closure, which creates a new function inside the function to modify the variables defined inside the function.
An internal function is return ed from the external function, so the operation of the internal variables of the function is realized.
Concepts: Functions that can access independent variables;
(2) Closure effect: 1. Solving the problem of global variable pollution;
2. Protecting variables, we can do some validation for variable assignment.
(3) Defects of closures: Defined functions can not be freed automatically because the return value is always in the invoked state, and memory has been occupied, resulting in waste of resources;
If you can avoid closures, try not to use them.
(4) Application
eg:
for(var i = 0; i < 10; i++){
setTimeout(function(j){
//var j = i
function inner(){
console.log(j);
}
return inner;
}(i), 1000);
}
tips: There is an event queue in js. The event queue for the loop takes precedence over setTimeout.
Therefore, without closures, the setTimeout function will not work properly.
The tasks in tips: js are divided into main tasks and minor tasks.
Main tasks (for, var, function... Etc);
Secondary tasks (setTimeout, setInterval... etc.);
eg:
function func(){
var num = Math.random();
var obj = {
setNum: function(value){
num = value;
},
getNum: function(){
return num;
}
}
return obj;
}
tips: When returning, an object is returned, and internal functions are stored in the object. By calling these internal function methods, variables in the function can be manipulated.
15, cache
Browser Cache
CDN, Content Delivery Network, Content Distribution Network;
Hardware cache (RAM, memory);
Code implementation cache:
Store data with an array or object, and find the results from the cache array in the case of tedious repetitive operations. Cache has no results to calculate.
eg:
Recursive optimization using caching and closures is illustrated by Fibonacci numbers.
function createFib(n){
var arr = []; // an array that acts as a cache
function fib(n){
var num = arr[n];
// Determine whether there is this number in the cache array, and if there is one, it will be used directly, and if not, it will be calculated.
if(!num){
if(n == 1 || n == 2){
num = 1;
}else{
num = fib(n - 1) + fib(n - 2);
}
arr[n] = num;
}
return num;
}
return fib(n);
}
createFib(5);
16. Sandbox Model
(1),Characteristic: The operation inside the sandbox will not affect the outside world.
(2),The basic model of sandbox: self-calling function( IIFE,Immediately Invoked Function Expression);
eg:
(function(){
var a = 10;
})()
(3),There are many ways to write self-calling function: as long as it can exist as a sentence and make self-calling;
(function (){})();
(function (){}());
+ function (){}();
! function (){}();
(4),Exposure interface operation
(function (w){
window.jQuery = window.$ = jQuery;
})(window)
tips: 1,The significance of data transmission is to achieve logical isolation.
2,When you compress code, you rename variables, but window Objects and other built-in objects cannot be renamed.
//At this time, if you use windows object directly, it will not be conducive to code compression, so you need to customize parameters to receive windows objects.
(5),Application of Sandbox Model:
1,Frame encapsulation;
2,Component;
3,Plug-in unit;
17. Call mode
1,Function call mode;
function fn(){
//this in function refers to a window object.
}
2,Object invocation mode;
var obj = {
sayHi:function(){
}
}
obj.sayHi();
3,Constructor call mode;
var obj = new Object();
4,Context ( context)Call mode;
lvalue Left value;
rvalue Right value; (Right value cannot be assigned as left value)
//Two ways: 1. apply;
2,call;
function.apply(obj , [a,b,c]);
function.call(obj , a, b, c, d ...);
tips: obj Hope for the function this The object pointed to, a,b,c,d Equivalent to the argument of the afferent function;
tips: The difference between them lies in the different forms of data transmission.
apply When the parameters are uncertain, call It is used when the number of parameters is determined.
tips: apply The parameters are placed in arrays, which makes it possible to apply Very commonly used;
//If the obj input type is a simple data type, it will automatically be converted to a complex data type.
eg:
test.apply(undefined);
test.apply(null); this Will point window;
eg:
//Turn Pseudo Array into True Array
var fakeArr = {
length:3,
0:a,
1:b,
2:c
}
var realArr = [];
realArr.push.apply(realArr , fakeArr);
//At this point, the data content of fakeArr will be stored in realArr and become a real array.
tips:The core usage is apply The array is automatically disassembled and used as a parameter to invoke the method.
eg:
function Animal(){}
function Dog(){
Animal.call(this);
}
var d = new Dog();
console.log(d);
tips: stay Dog Inside the function, use call Method will Animal Of this Point to the instantiated object;
18. Patterns for creating objects
(1),Factory mode
eg:
function createPerson(name, age){
var obj = {};
obj.name = name;
obj.age = age;
console.log(this);
return obj;
}
var p = createPerson("Jacky Cheung", 50);
var p1 = createPerson("Aaron Kwok", 50);
tips: The factory pattern is similar to the constructor, but the function of the factory pattern builds an object by itself, assigns the value to the object by passing parameters, and finally returns the object as a return value.
(2),Constructor pattern( constructor)
eg:
function Person(name, age){
this.name = name;
this.age = age;
}
var p = new Person("Lee Hom", 30);
(3),Parasitic pattern
eg:
function createPerson(name, age){
var obj = {};
obj.name = name;
obj.age = age;
console.log(this);
return obj;
}
var p = new createPerson("Lau Andy", 60);
tips: The difference between parasitic mode and factory mode is that the way objects are created parasitic mode uses new Method: The factory mode is used to transfer parameters directly to the function.
19. Array traversal (forEach and map)
(1),forEach
arr.forEach(value , index , arr){};
tips: value For array elements, index Index elements, arr For the current traversal array (generally not added);
(2),map(Mapping)
arr.map(value , index , arr){};
tips: map The difference is that map With a return value, the result returned by the operation performed in it will be stored in a new array, which will be used as the return value. return;
eg:
var arr = [a,b,c,d];
var strArr = arr.map(String);
tips: Final results strArr It will be an array of strings.
20. Strict Model
"use strict"
'use strict'
1,Declare variables in strict mode var Can not be omitted;
2,No duplication of formal parameters is allowed under strict mode.
3,In the early strict mode, the attribute names of objects can not be repeated.
//But in ECMAScript 6, this is supported!
4,Octal system is not allowed to be used in strict mode.
eg:
var a = 010;
console.log(a);
tips: a When assigning a value, the first zero indicates that the number is octal.
5,In strict mode, eval Functions have their own scopes
eg:
eval("var a = 10; console.log(a)");
console.log(a);
21,Object.defineProperty
Object.defineProperty(Objects that need to add attributes , "Attribute name" , {
writable:true,
enumerable:true,
configurable:true,
value:"Attribute value";
})
(1),Writable(writable): Default is false,Can't be assigned
value Set the value of the property;
· setter and getter
//If only setter writes attributes, only assignments can be made, and no values can be obtained.
//If only getter read-only properties are read-only, they cannot be assigned
tips: setter and getter General discord writable Also value Use together;
getter and setter Can do the operation of checking data!
tips: That is to say, yes. writable and value There will be no setter and getter;
tips: In use getter and setter When written get or set;
(2),Ergodicity(enumerable): Default is false, Can not be traversed;
(3),Deleting ability(configurable): Default is false,Can not be deleted;
eg:
Object.defineProperty(obj, "job", {
enumerable: true,
configurable: true,
get:function () {
return jobValue;
},
set:function(value){
jobValue = value;
}
});
eg:
Object.defineProperty(obj, "job", {
writable: true,
enumerable: true,
configurable: true,
value: "singer",
});
22. Object-Oriented Programming Details
1,Object-oriented programming is mainly divided into two parts: the first part is the constructor and the second part is the prototype.
2,Some initialization operations are stored in the constructor, and the methods needed by the object are stored in the prototype as far as possible.
3,When the constructor is initialized, the necessary method is called to initialize the instantiated object. The execution code can be written as a general class, and the fine classes are written in the prototype. The prototype provides the method of initializing the general class.
eg:
//Write only one this.init() in the constructor.
//In the prototype, the init method calls other methods of the current prototype, thus realizing the encapsulation of the calling method.
4,After object-oriented encapsulation, constructors and prototypes can be encapsulated in sandbox mode, so that the functions created will not affect the outside world and have high security.
5,When writing a prototype, manually make the prototype constructor Point to a custom constructor;
5,The sandbox mode created also needs to provide an interface for external calls.
eg:
(function (w){
function jQuery(){}
jQuery.prototype = {
constructor:jQuery, //—— Manually point the constructor to jQuery
init:function (){
this.add();
this.push();
},
add:function(){},
push:function(){}
}
window.jQuery = window.$ = jQuery;
})(window)