Data Type
JavaScript is a weak-type language, but it is not without types. JavaScript can recognize the following 7 different types of values:
Basic data types
1.Boolean
2.Number
3.String
4.null
5.undefined
6.Symbol
Object
1.Array
2.RegExp
3.Date
4.Math
5....
You can use typeof to determine the data type. The operator returns a string, but not all results returned are in line with expectations.
typeof false // "boolean"typeof .2 // "number"typeof NaN // "number"typeof '' // "string"typeof undefined // "undefined"typeof Symbol() // "symbol"typeof new Date() // "object"typeof [] // "object"typeof alert // "function"typeof null // "object"typeof not_defined_var // "undefined"
variable
In the application, use variables to name the value. The name of the variable is called identifiers
statement
1. Use the keyword var: function scope
2. Use keyword let: block scope local variable
3. Direct use: global scope
var global_var = 1;function fn () {var fn_var = 2;if(fn_var > 10){let block_var = 3;global_var2 = 4;}}Only declare no assignment, the default value of variable is undefined
The const keyword can declare immutable variables, and is also block scoped. The understanding of immutable objects requires attention
const num = 1;const obj = {prop: 'value'};num = 2; // Uncaught TypeError: Assignment to constant variable.obj['prop'] = 'value2';obj = []; // Uncaught TypeError: Assignment to constant variable.Variable enhancement
JavaScript can refer to variables declared later without throwing different concepts. This concept is called variable declaration promotion (hoisting)
console.log(a); // undefinedvar a = 2;
Equivalent to
var a;console.log(a);a = 2;
function
A function is a subroutine that can be called by external code (or recursively called by the function itself).
Define functions
1. Function declaration
2. Function expressions
3. Function constructor
4. Arrow function
function fn(){}var fn = function(){}var fn = new Function(arg1, arg2, ... argN, funcBody)var fn = (param) => {}arguments
1.arguments: An array-like object that contains parameters passed to the current execution function
2.arguments.length: The number of parameters passed to the function
3.arguments.caller: Call the function that currently executes the function
4.arguments.callee: The function currently being executed
function foo() {return arguments;}foo(1, 2, 3); // Arguments[3] // { "0": 1, "1": 2, "2": 3 }rest
function foo(...args) {return args;}foo(1, 2, 3); // Array[3]// [1, 2, 3]function fn(a, b, ...args){return args;}fn(1, 2, 3, 4, 5); // Array[3] // [3, 4, 5]default
The default values can be agreed upon when defining the parameters of the function.
function fn (a = 2, b = 3) {return a + b;}fn(2, 3); // 5fn(2); // 5fn(); // 5Object
Objects in JavaScript are variable keyed collections
Define objects
1. Literal
2. Constructor
var obj = {prop: 'value',fn: function(){}};var date = new Date();Constructor
There is no difference between a constructor and a normal function. Calling with the new keyword is a constructor. Using the constructor can instantiate an object.
There are two possible returns of the function
1. Explicitly call return to return the evaluation of the expression after return
2. No return is called and returned undefined
function People(name, age) {this.name = name;this.age = age;}var people = new People('Byron', 26);Constructor returns value
1. No return value
2. Simple data type
3. Object Type
The constructor returns an instance of the constructor in the first two cases. This feature is used by instantiating the object.
The third constructor performs the same as the ordinary function, and returns the result of the expression after return
prototype
1. Each function has an object attribute of prototype, and there is a constructor attribute in the object, which points to the function itself by default.
2. Each object has a __proto__ attribute, and the zodiac pointes to the prototype of its parent type
function Person(name) {this.name = name;}Person.prototype.print = function () {console.log(this.name);};var p1 = new Person('Byron');var p2 = new Person('Casper');p1.print();p2.print();this and scope
The scope can be understood in a popular way
1. Who am I
2. What kind of horsemen do I have
Who am I answered this
The horseman is my local variable
This scene
Normal functions
1. Strict mode: undefined
2. Non-strict mode: global object
3.Node: global
4. Browser: window
Constructor: An instance of an object
Object method: object itself
call & apply
1.fn.call(context, arg1, arg2, …, argn)
2.fn.apply(context, args)
function isNumber(obj) {return Object.prototype.toString.call(obj) === '[object Number]';}Function.prototype.bind
bind returns a new function, the scope of the function is the bind parameter
function fn() {this.i = 0;setInterval(function () {console.log(this.i++);}.bind(this), 500)}fn(); () => {}Arrow function is a new feature provided by ES6, it is abbreviated function expression, with lexical scope and this value
function fn() {this.i = 0;setInterval(() => {console.log(this.i++);}, 500)}fn();inherit
In JavaScript scenario, inheritance has two goals, and the subclass needs to get the parent class:
1. Object properties
2. Object method
function inherits(child, parent) {var _proptotype = Object.create(parent.prototype);_proptotype.constructor = child.prototype.constructor;child.prototype = _proptotype;}function People(name, age) {this.name = name;this.age = age;}People.prototype.getName = function () {return this.name;}function English(name, age, language) {People.call(this, name, age);this.language = language;}inherits(English, People);English.prototype.introduce = function () {console.log('Hi, I am ' + this.getName());console.log('I speak ' + this.language);}function Chinese(name, age, language) {People.call(this, name, age);this.language = language;}inherits(Chinese, People);Chinese.prototype.introduce = function () {console.log('Hello, I am' + this.getName());console.log('I said' + this.language);}var en = new English('Byron', 26, 'English');var cn = new Chinese('Salad Oil', 27, 'Chinese');en.introduce();cn.introduce();ES6 class and inheritance
"use strict";class People{constructor(name, age){this.name = name;this.age = age;}getName(){return this.name;}}class English extends People{constructor(name, age, language){super(name, age);this.language = language;}introduce(){console.log('Hi, I am ' + this.getName());console.log('I speak ' + this.language);}}let en = new English('Byron', 26, 'English');en.introduce();grammar
label statement
loop:
for (var i = 0; i < 10; i++) {for (var j = 0; j < 5; j++) {console.log(j);if (j === 1) {break loop;}}}console.log(i);Statements and expressions
var x = { a:1 };{ a:1 }{ a:1, b:2 }Execute the function immediately
( function() {}() );( function() {} )();[ function() {}() ];~ function() {}();! function() {}();+ function() {}();- function() {}();delete function() {}();typeof function() {}();void function() {}();new function() {}();new function() {}();var f = function() {}();1, function() {}();1 ^ function() {}();1 > function() {}();Advanced functions
Higher-order functions are functions that treat functions as parameters or return values as functions.
Callback function
[1, 2, 3, 4].forEach(function(item){console.log(item);});Closure
The closure consists of two parts
1. Function
2. Environment: Local variables within scope when function creation
function makeCounter(init) {var init = init || 0;return function(){return ++init;}}var counter = makeCounter(10);console.log(counter());console.log(counter());console.log(counter());Typical error
for (var i = 0; i < doms.length; i++) {doms.eq(i).on('click', function (ev) {console.log(i);});} for (var i = 0; i < doms.length; i++) {(function (i) {doms.eq(i).on('click', function (ev) {console.log(i);});})(i);}Lazy Functions
function eventBinderGenerator() {if (window.addEventListener) {return function (element, type, handler) {element.addEventListener(type, hanlder, false);}} else {return function (element, type, handler) {element.attachEvent('on' + type, handler.bind(element, window.event));}}} var addEvent = eventBinderGenerator();Curry
A way to allow the use of partial parameters to generate functions
function isType(type) {return function(obj){return Object.prototype.toString.call(obj) === '[object '+ type +']';}}var isNumber = isType('Number');console.log(isNumber(1));console.log(isNumber('s'));var isArray = isType('Array');console.log(isArray(1));console.log(isArray([1, 2, 3])); function f(n) {return n * n;}function g(n) {return n * 2;}console.log(f(g(5)));function pipe(f, g) {return function () {return f.call(null, g.apply(null, arguments));}}var fn = pipe(f, g);console.log(fn(5));Tail recursion
1. Tail call means that the last step of a function is to call another function
2. The function call itself, called recursion
3. If the tail calls itself, it is called tail recursion
Recursion is prone to "stack overflow" errors (stack overflow)
function factorial(n) {if (n === 1) return 1;return n * factorial(n - 1);}factorial(5) // 120But for tail recursion, since there is only one call record, the "stack overflow" error will never occur
function factorial(n, total) {if (n === 1) return total;return factorial(n - 1, n * total);}factorial(5, 1) // 120Currying reduces parameters
function currying(fn, n) {return function (m) {return fn.call(this, m, n);};}function tailFactorial(n, total) {if (n === 1) return total;return tailFactorial(n - 1, n * total);}const factorial = currying(tailFactorial, 1);factorial(5) // 120Anti-Curriization
Function.prototype.uncurry = function () {return this.call.bind(this);};push generalization
var push = Array.prototype.push.uncurry();var arr = [];push(arr, 1);push(arr, 2);push(arr, 3);console.log(arr);
The above content is the full description of the exquisite classic examples of JavaScript language (compilation) introduced to you by the editor. I hope it will be helpful to everyone!