0% found this document useful (0 votes)
6K views

1 JavaScript面试真题-210页

Uploaded by

puerem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6K views

1 JavaScript面试真题-210页

Uploaded by

puerem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 210




JavaScript



1


1 let intNum = 55 // 10 55
2 let num1 = 070 // 8 56
3 let hexNum1 = 0xA //16 10

1 let floatNum1 = 1.1;


2 let floatNum2 = 0.1;
3 let floatNum3 = .1; //
4 let floatNum = 3.125e7; // 31250000

NaN

1 console.log(0/0); // NaN
2 console.log(-0/+0); // NaN



Undefined undefined var let


undefined

1 let message;
2 console.log(message == undefined); // true

undefined

2
1 let message; // undefined
2
3 console.log(message); // "undefined"
4 console.log(age); //



1 let firstName = "John";


2 let lastName = 'Jacob';
3 let lastName = `Jingleheimerschmidt`

1 let lang = "Java";


2 lang = lang + "Script"; //



Null null

typeof null "object"

1 let car = null;


2 console.log(typeof car); // "object"

undefined null

1 console.log(null == undefined); // true

null

3


Boolean true false

Boolean

1 true false
2 String ""
3 Number 0 NaN
4 Object null
5 Undefined N/A undefined



1 let genericSymbol = Symbol();


2 let otherGenericSymbol = Symbol();
3 console.log(genericSymbol == otherGenericSymbol); // false
4
5 let fooSymbol = Symbol('foo');
6 let otherFooSymbol = Symbol('foo');
7 console.log(fooSymbol == otherFooSymbol); // false


Object



object

4
1 let person = {
2 name: "Nicholas",
3 "age": 29,
4 5: true
5 };



JavaScript

1 let colors = ["red", 2, {age: 20 }]


2 colors.push(2)



Function Function

1 //
2 function sum (num1, num2) {
3 return num1 + num2;
4 }

1 let sum = function(num1, num2) {


2 return num1 + num2;
3 };

5
1 let sum = (num1, num2) => {
2 return num1 + num2;
3 };



Date RegExp Map Set





1 let a = 10;
2 let b = a; //
3 b = 20;
4 console.log(a); // 10

a a b

6


1 var obj1 = {}
2 var obj2 = obj1;
3 obj2.name = "Xxx";
4 console.log(obj1.name); // xxx

obj1
obj2 obj2 obj1

7


8























9


10




11





12
HTML XML

HTML XML DOM

1 <html>
2 <head>
3 <title>Page</title>
4 </head>
5 <body>
6 <p>Hello World!</p >
7 </body>
8 </html>

DOM DOM

1 <div>
2 <p title="title">
3 content
4 </p >
5 </div>

div p content title


DOM

Jquery zepto DOM vue Angular React


DOM DOM

DOM

DOM

13




1 const divEl = document.createElement("div");



1 const textEl = document.createTextNode("content");



DOM

1 const fragment = document.createDocumentFragment();

DocumentFragment DocumentFragment



14
1 const dataAttribute = document.createAttribute('custom');
2 consle.log(dataAttribute);





css DOM

1 document.querySelector('.element')
2 document.querySelector('#element')
3 document.querySelector('div')
4 document.querySelector('[name="username"]')
5 document.querySelector('div + p > span')

null



Element

1 const notLive = document.querySelectorAll("p");

NodeList

DOM

15
1 document.getElementById('id '); id
2 document.getElementsByClassName('class '); class
3 document.getElementsByTagName(' ');
4 document.getElementsByName('name ');
5 document/element.querySelector('CSS ');
6 document/element.querySelectorAll('CSS ');
7 document.documentElement; HTML
8 document.body; BODY
9 document.all[''];

DOM
parentNode childNodes firstChild lastChild nextSibling previo
usSibling





DOM HTML DOM

16
1 // <p id="p">...</p >
2 var p = document.getElementById('p');
3 // abc:
4 p.innerHTML = 'ABC'; // <p id="p">ABC</p >
5 // HTML:
6 p.innerHTML = 'ABC <span style="color:red">RED</span> XYZ';
7 // <p>...</p >



HTML HTML

1 // <p id="p-id">...</p >


2 var p = document.getElementById('p-id');
3 // :
4 p.innerText = '<script>alert("Hi")</script>';
5 // HTML <script> :
6 // <p id="p-id">&lt;script&gt;alert("Hi")&lt;/script&gt;</p >

innerText textContent



DOM style CSS -

1 // <p id="p-id">...</p >


2 const p = document.getElementById('p-id');
3 // CSS:
4 p.style.color = '#ff0000';
5 p.style.fontSize = '20px'; //
6 p.style.paddingTop = '2em';





17
<div></div> innerHTML = '<span>chil
d</span>' DOM DOM

innerHTML



1 <!-- HTML -->


2 <p id="js">JavaScript</p >
3 <div id="list">
4 <p id="java">Java</p >
5 <p id="python">Python</p >
6 <p id="scheme">Scheme</p >
7 </div>

1 const js = document.getElementById('js')
2 js.innerHTML = "JavaScript"
3 const list = document.getElementById('list');
4 list.appendChild(js);

HTML

1 <!-- HTML -->


2 <div id="list">
3 <p id="java">Java</p >
4 <p id="python">Python</p >
5 <p id="scheme">Scheme</p >
6 <p id="js">JavaScript</p > <!-- -->
7 </div>

DOM js

18
1 const list = document.getElementById('list'),
2 const haskell = document.createElement('p');
3 haskell.id = 'haskell';
4 haskell.innerText = 'Haskell';
5 list.appendChild(haskell);



1 parentElement.insertBefore(newElement, referenceElement)

referenceElement



1 const div = document.getElementById('id')


2 div.setAttribute('class', 'white');//



removeChild

1 // :
2 const self = document.getElementById('to-be-removed');
3 // :
4 const parent = self.parentElement;
5 // :
6 const removed = parent.removeChild(self);
7 removed === self; // true

19



BOM

DOM BOM


Bom window

20
window

window

1 var name = 'js ';


2 function lookName(){
3 alert(this.name);
4 }
5
6 console.log(window.name); //js
7 lookName(); //js
8 window.lookName(); //js

moveBy(x,y)

moveTo(x,y)

resizeBy(w,h)

resizeTo(w,h)

scrollTo(x,y)

scrollBy(x,y)

window.open() url

window.open()

1 window.open('htttp://www.vue3js.cn','topFrame')
2 ==> < a href=" " target="topFrame"></ a>

window.open() window

1 const myWin = window.open('http://www.vue3js.cn','myWin')

21
window.close() window.open()

window opener


url

1 http://foouser:[email protected]:80/WileyCDA/?q=javascript#contents

location

hash location URL

location.reload()

true



22
navigator

navigator

23


24

history URL
URL

history.go()

1 history.go('maixaofei.com')

1 history.go(3) //
2 history.go(-1) //

history.forward()

history.back()

history.length



25

true

JavaScript

1 let result1 = (true == 1); // true

1 let result1 = ("55" == 55); // true

valueOf()

1 let obj = {valueOf:function(){return 1}}


2 let result1 = (obj == 1); // true

null undefined

26
1 let result1 = (null == undefined ); // true

NaN false

1 let result1 = (NaN == NaN ); // false

true

1 let obj1 = {name:"xxx"}


2 let obj2 = {name:"xxx"}
3 let result1 = (obj1 == obj2 ); // false


true

1 let result1 = ("55" === 55); // false


2 let result2 = (55 === 55); // true

undefined null

27
1 let result1 = (null === null) //true
2 let result2 = (undefined === undefined) //true



1 let result1 = ("55" === 55); // false


2 let result2 = (55 === 55); // true

null undefined true false

1 let result1 = (null == undefined ); // true


2 let result2 = (null === undefined); // false



1 '' == '0' // false


2 0 == '' // true
3 0 == '0' // true
4
5 false == 'false' // false
6 false == '0' // true
7
8 false == undefined // false
9 false == null // false
10 null == undefined // true
11
12 ' \t\r\n' == 0 // true

null ==

28
1 const obj = {};
2
3 if(obj.x == null){
4 console.log("1"); //
5 }

1 if(obj.x === null || obj.x === undefined) {


2 ...
3 }

null undefined




typeof

29
1 typeof operand
2 typeof(operand)

operand

1 typeof 1 // 'number'
2 typeof '1' // 'string'
3 typeof undefined // 'undefined'
4 typeof true // 'boolean'
5 typeof Symbol() // 'symbol'
6 typeof null // 'object'
7 typeof [] // 'object'
8 typeof {} // 'object'
9 typeof console // 'object'
10 typeof console.log // 'function'

typeof null object JavaScript


Bug null null

null typeof null


if null ===null

typeof function
object

typeof if(a) a

1 if(typeof a != 'undefined'){
2 //
3 }


instanceof prototype

30
1 object instanceof constructor

object constructor

new instanceof

1 //
2 let Car = function() {}
3 let benz = new Car()
4 benz instanceof Car // true
5 let car = new String('xxx')
6 car instanceof String // true
7 let str = 'xxx'
8 str instanceof String // false

instanceof

1 function myInstanceof(left, right) {


2 // typeof false
3 if(typeof left !== 'object' || left === null) return false;
4 // getProtypeOf Object API
5 let proto = Object.getPrototypeOf(left);
6 while(true) {
7 if(proto === null) return false;
8 if(proto === right.prototype) return true;// tru
e
9 proto = Object.getPrototypeof(proto);
10 }
11 }

true false


typeof instanceof

typeof instanceof

instanceof

31
typeof null
function

Object.prototype.toString
“[object Xxx]”

1 Object.prototype.toString({}) // "[object Object]"


2 Object.prototype.toString.call({}) // call ok
3 Object.prototype.toString.call(1) // "[object Number]"
4 Object.prototype.toString.call('1') // "[object String]"
5 Object.prototype.toString.call(true) // "[object Boolean]"
6 Object.prototype.toString.call(function(){}) // "[object Function]"
7 Object.prototype.toString.call(null) //"[object Null]"
8 Object.prototype.toString.call(undefined) //"[object Undefined]"
9 Object.prototype.toString.call(/123/g) //"[object RegExp]"
10 Object.prototype.toString.call(new Date()) //"[object Date]"
11 Object.prototype.toString.call([]) //"[object Array]"
12 Object.prototype.toString.call(document) //"[object HTMLDocument]"
13 Object.prototype.toString.call(window) //"[object Window]"

toString

1 function getType(obj){
2 let type = typeof obj;
3 if (type !== "object") { // typeof
4 return type;
5 }
6 // typeof object
7 return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/,
'$1');
8 }

32
1 getType([]) // "Array" typeof [] object toString
2 getType('123') // "string" typeof
3 getType(window) // "Window" toString
4 getType(null) // "Null" typeof null object toString
5 getType(undefined) // "undefined" typeof
6 getType() // "undefined" typeof
7 getType(function(){}) // "function" typeof
8 getType(/123/g) //"RegExp" toString




JavaScript

prototype

prototype

33
1 function doSomething(){}
2 console.log( doSomething.prototype );

1 {
2 constructor: ƒ doSomething(),
3 __proto__: {
4 constructor: ƒ Object(),
5 hasOwnProperty: ƒ hasOwnProperty(),
6 isPrototypeOf: ƒ isPrototypeOf(),
7 propertyIsEnumerable: ƒ propertyIsEnumerable(),
8 toLocaleString: ƒ toLocaleString(),
9 toString: ƒ toString(),
10 valueOf: ƒ valueOf()
11 }
12 }

constructor



__proto__
prototype

34
1 function Person(name) {
2 this.name = name;
3 this.age = 18;
4 this.sayName = function() {
5 console.log(this.name);
6 }
7 }
8 //
9 var person = new Person('person')

35
Person Person.prototype

person person __proto__ Person


Person.prototype.__proto__ Person.prototype
Object Object.prototype

Person.__proto__ anonymous

36
Function.prototype Function.__proto__ anonymous
null



__proto__

__proto__ prototype

1 person1.__proto__ === Person.prototype

Function

1 Person.__proto__ === Function.prototype

Object

1 Person.prototype.__proto__ === Object.prototype

Function

37
1 Object.__proto__ === Function.prototype

Object __proto__ null null

1 Object.prototype.__proto__ === null

Object Object null

Object Function

Object Function

Function __proto__ Object





38
1 function myFunction() {
2 let inVariable = " ";
3 }
4 myFunction();//
5 console.log(inVariable); // Uncaught ReferenceError: inVariable is not defi
ned

myFunction inVariable



1 //
2 var greeting = 'Hello World!';
3 function greet() {
4 console.log(greeting);
5 }
6 // 'Hello World!'
7 greet();



39
1 function greet() {
2 var greeting = 'Hello World!';
3 console.log(greeting);
4 }
5 // 'Hello World!'
6 greet();
7 // Uncaught ReferenceError: greeting is not defined
8 console.log(greeting);



let const var let const

1 {
2 //
3 let greeting = 'Hello World!';
4 var lang = 'English';
5 console.log(greeting); // Prints 'Hello World!'
6 }
7 // 'English'
8 console.log(lang);
9 // Uncaught ReferenceError: greeting is not defined
10 console.log(greeting);



JavaScript

40
1 var a = 2;
2 function foo(){
3 console.log(a)
4 }
5 function bar(){
6 var a = 3;
7 foo();
8 }
9 bar()

JavaScript foo bar


Javascript Javascript

41
42
1 var sex = ' ';
2 function person() {
3 var name = ' ';
4 function student() {
5 var age = 18;
6 console.log(name); //
7 console.log(sex); //
8 }
9 student();
10 console.log(age); // Uncaught ReferenceError: age is not defined
11 }
12 person();

student name person

student sex person

person age

43

this JavaScript

this

this

1 function baz() {
2 // baz
3 //
4
5 console.log( "baz" );
6 bar(); // <-- bar
7 }
8
9 function bar() {
10 // baz --> bar
11 // baz
12
13 console.log( "bar" );
14 foo(); // <-- foo
15 }
16
17 function foo() {
18 // baz --> bar --> foo
19 // bar
20
21 console.log( "foo" );
22 }
23
24 baz(); // <-- baz

this this

44
1 var a = 10;
2 var obj = {
3 a: 20
4 }
5
6 function fn() {
7 this = obj; // this
8 console.log(this.a);
9 }
10
11 fn();


this



person this

1 var name = 'Jenny';


2 function person() {
3 return this.name;
4 }
5 console.log(person()); //Jenny

Jenny window this


window Jenny

undefined

45


this

1 function test() {
2 console.log(this.x);
3 }
4
5 var obj = {};
6 obj.x = 1;
7 obj.m = test;
8
9 obj.m(); // 1

this

1 var o = {
2 a:10,
3 b:{
4 fn:function(){
5 console.log(this.a); //undefined
6 }
7 }
8 }
9 o.b.fn();

this b b a undefined

46
1 var o = {
2 a:10,
3 b:{
4 a:12,
5 fn:function(){
6 console.log(this.a); //undefined
7 console.log(this); //window
8 }
9 }
10 }
11 var j = o.b.fn;
12 j();

this window this


fn b fn j window



new this

1 function test() {
2 this.x = 1;
3 }
4
5 var obj = new test();
6 obj.x // 1

new this

new return this

47
1 function fn()
2 {
3 this.user = 'xxx';
4 return {};
5 }
6 var a = new fn();
7 console.log(a.user); //undefined

this

1 function fn()
2 {
3 this.user = 'xxx';
4 return 1;
5 }
6 var a = new fn;
7 console.log(a.user); //xxx

null new

1 function fn()
2 {
3 this.user = 'xxx';
4 return null;
5 }
6 var a = new fn;
7 console.log(a.user); //xxx



apply() call() bind()


this

48
1 var x = 0;
2 function test() {
3 console.log(this.x);
4 }
5
6 var obj = {};
7 obj.x = 1;
8 obj.m = test;
9 obj.m.apply(obj) // 1

apply call bind


this

1 const obj = {
2 sayThis: () => {
3 console.log(this);
4 }
5 };
6
7 obj.sayThis(); // window JavaScript sayThis
this window
8 const globalSay = obj.sayThis;
9 globalSay(); // window global

this this

49
1 const button = document.getElementById('mngb');
2 button.addEventListener('click', ()=> {
3 console.log(this === window) // true
4 this.innerHTML = 'clicked button'
5 })

this button this window

this window

1 Cat.prototype.sayName = () => {
2 console.log(this === window) //true
3 return this.name
4 }
5 const cat = new Cat('mm');
6 cat.sayName()





50
1 function foo() {
2 console.log( this.a );
3 }
4
5 var obj1 = {
6 a: 2,
7 foo: foo
8 };
9
10 var obj2 = {
11 a: 3,
12 foo: foo
13 };
14
15 obj1.foo(); // 2
16 obj2.foo(); // 3
17
18 obj1.foo.call( obj2 ); // 3
19 obj2.foo.call( obj1 ); // 2



51
1 function foo(something) {
2 this.a = something;
3 }
4
5 var obj1 = {
6 foo: foo
7 };
8
9 var obj2 = {};
10
11 obj1.foo( 2 );
12 console.log( obj1.a ); // 2
13
14 obj1.foo.call( obj2, 3 );
15 console.log( obj2.a ); // 3
16
17 var bar = new obj1.foo( 4 );
18 console.log( obj1.a ); // 2
19 console.log( bar.a ); // 4

>

 new

new apply call

1 function foo(something) {
2 this.a = something;
3 }
4
5 var obj1 = {};
6
7 var bar = foo.bind( obj1 );
8 bar( 2 );
9 console.log( obj1.a ); // 2
10
11 var baz = new bar( 3 );
12 console.log( obj1.a ); // 2
13 console.log( baz.a ); // 3

52
bar new bar(3) obj1.a n
ew bar() this

new >




JavaScript new

1 function Person(name, age){


2 this.name = name;
3 this.age = age;
4 }
5 Person.prototype.sayName = function () {
6 console.log(this.name)
7 }
8 const person1 = new Person('Tom', 20)
9 console.log(person1) // Person {name: "Tom", age: 20}
10 t.sayName() // 'Tom'

new Person

53
new Person

1 function Test(name) {
2 this.name = name
3 return 1
4 }
5 const t = new Test('xxx')
6 console.log(t.name) // 'xxx'

1 function Test(name) {
2 this.name = name
3 console.log(this) // Test { name: 'xxx' }
4 return { age: 26 }
5 }
6 const t = new Test('xxx')
7 console.log(t) // { age: 26 }
8 console.log(t.name) // 'undefined'


new

obj

this obj

54
1 function Person(name, age){
2 this.name = name;
3 this.age = age;
4 }
5 const person1 = new Person('Tom', 20)
6 console.log(person1) // Person {name: "Tom", age: 20}
7 t.sayName() // 'Tom'

55

new

new

1 function mynew(Func, ...args) {


2 // 1.
3 const obj = {}
4 // 2.
5 obj.__proto__ = Func.prototype
6 // 3. this
7 let result = Func.apply(obj, args)
8 // 4.
9 return result instanceof Object ? result : obj
10 }

1 function mynew(func, ...args) {


2 const obj = {}
3 obj.__proto__ = func.prototype
4 let result = func.apply(obj, args)
5 return result instanceof Object ? result : obj
6 }
7 function Person(name, age) {
8 this.name = name;
9 this.age = age;
10 }
11 Person.prototype.say = function () {
12 console.log(this.name)
13 }
14
15 let p = mynew(Person, "huihui", 123)
16 console.log(p) // Person {name: "huihui", age: 123}
17 p.say() // huihui

new



56

call apply bind
this

this

1 var name = "lucy";


2 var obj = {
3 name: "martin",
4 say: function () {
5 console.log(this.name);
6 }
7 };
8 obj.say(); // martin this obj
9 setTimeout(obj.say,0); // lucy this window

say martin

say setTimeout
this window lucy

this obj this

1 setTimeout(obj.say.bind(obj),0); //martin this obj

57

apply call bind



apply this

this this

1 function fn(...args){
2 console.log(this,args);
3 }
4 let obj = {
5 myname:" "
6 }
7
8 fn.apply(obj,[1,2]); // this obj
9 fn(1,2) // this window

null undefined window

1 fn.apply(null,[1,2]); // this window


2 fn.apply(undefined,[1,2]); // this window



call this

apply this this

58
1 function fn(...args){
2 console.log(this,args);
3 }
4 let obj = {
5 myname:" "
6 }
7
8 fn.call(obj,1,2); // this obj
9 fn(1,2) // this window

null undefined window

1 fn.call(null,[1,2]); // this window


2 fn.call(undefined,[1,2]); // this window



this

this this

1 function fn(...args){
2 console.log(this,args);
3 }
4 let obj = {
5 myname:" "
6 }
7
8 const bindFn = fn.bind(obj); // this obj bind

9 bindFn(1,2) // this obj


10 fn(1,2) // this window



apply call bind

59
this

this undefined nul


l window

apply call apply call


bind

bind apply call


bind

this

1 // bind
2 fn.bind(obj,1,2)()
3
4 // bind
5 fn.bind(obj,1)(2)

new

60
1 Function.prototype.myBind = function (context) {
2 //
3 if (typeof this !== "function") {
4 throw new TypeError("Error");
5 }
6
7 //
8 const args = [...arguments].slice(1),
9 fn = this;
10
11 return function Fn() {
12
13 //
14 return fn.apply(this instanceof Fn ? new fn(...arguments) : contex
t, args.concat(...arguments));
15 }
16 }




Javascript Javascr
ipt

window this

61
eval





62
This Binding

1 ExecutionContext = {
2 ThisBinding = <this value>, // this
3 LexicalEnvironment = { ... }, //
4 VariableEnvironment = { ... }, //
5 }



this this



null
this

arguments

63
1 GlobalExectionContext = { //
2 LexicalEnvironment: { //
3 EnvironmentRecord: { //
4 Type: "Object", //
5 //
6 outer: <null> //
7 }
8 }
9
10 FunctionExectionContext = { //
11 LexicalEnvironment: { //
12 EnvironmentRecord: { //
13 Type: "Declarative", //
14 // //
15 outer: <Global or outer function environment reference>
16 }
17 }



let const
var

1 let a = 20;
2 const b = 30;
3 var c;
4
5 function multiply(e, f) {
6 var g = 20;
7 return e * f * g;
8 }
9
10 c = multiply(20, 30);

64
1 GlobalExectionContext = {
2
3 ThisBinding: <Global Object>,
4
5 LexicalEnvironment: { //
6 EnvironmentRecord: {
7 Type: "Object",
8 //
9 a: < uninitialized >,
10 b: < uninitialized >,
11 multiply: < func >
12 }
13 outer: <null>
14 },
15
16 VariableEnvironment: { //
17 EnvironmentRecord: {
18 Type: "Object",
19 //
20 c: undefined,
21 }
22 outer: <null>
23 }
24 }
25
26 FunctionExectionContext = {
27
28 ThisBinding: <Global Object>,
29
30 LexicalEnvironment: {
31 EnvironmentRecord: {
32 Type: "Declarative",
33 //
34 Arguments: {0: 20, 1: 30, length: 2},
35 },
36 outer: <GlobalLexicalEnvironment>
37 },
38
39 VariableEnvironment: {
40 EnvironmentRecord: {
41 Type: "Declarative",
42 //
43 g: undefined
44 },
45 outer: <GlobalLexicalEnvironment>

65
46 }
47
}

let const a b var


undefined

undefined var uninitialized


let const



Javascript undefined





Javascript

66
1 let a = 'Hello World!';
2 function first() {
3 console.log('Inside first function');
4 second();
5 console.log('Again inside first function');
6 }
7 function second() {
8 console.log('Inside second function');
9 }
10 first();
11 console.log('Inside Global Execution Context');

first

first second

second first

first



67

javascript HTML

DOM

DOM

68
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Event Bubbling</title>
6 </head>
7 <body>
8 <button id="clickMe">Click Me</button>
9 </body>
10 </html>

button

1 var button = document.getElementById('clickMe');


2
3 button.onclick = function() {
4 console.log('1.Button');
5 };
6 document.body.onclick = function() {
7 console.log('2.body');
8 };
9 document.onclick = function() {
10 console.log('3.document');
11 };
12 window.onclick = function() {
13 console.log('4.window');
14 };

1 1.button
2 2.body
3 3.document
4 4.window

button

69




1 <input type="button" onclick="fun()">

JS

1 var btn = document.getElementById('.btn');


2 btn.onclick = fun;



DOM0

1 <input type="button" id="btn" onclick="fun1()">


2
3 var btn = document.getElementById('.btn');
4 btn.onclick = fun2;

70
btn

DOM0 null

1 btn.onclick = null;



document

document

1 addEventListener(eventType, handler, useCapture)

1 removeEventListener(eventType, handler, useCapture)

eventType

handler

useCapture boolean false

71
1 var btn = document.getElementById('.btn');
2 btn.addEventListener(‘click’, showMessage, false);
3 btn.removeEventListener(‘click’, showMessage, false);



DOM

1 btn.addEventListener(‘click’, showMessage1, false);


2 btn.addEventListener(‘click’, showMessage2, false);
3 btn.addEventListener(‘click’, showMessage3, false);

useCapture true

1 <div id='div'>
2 <p id='p'>
3 <span id='span'>Click Me!</span>
4 </p >
5 </div>

1 var div = document.getElementById('div');


2 var p = document.getElementById('p');
3
4 function onClickFn (event) {
5 var tagName = event.currentTarget.tagName;
6 var phase = event.eventPhase;
7 console.log(tagName, phase);
8 }
9
10 div.addEventListener('click', onClickFn, false);
11 p.addEventListener('click', onClickFn, false);

72
eventPhase

Click Me!

1 P 3
2 DIV 3

p div p

true

1 div.addEventListener('click', onClickFn, true);


2 p.addEventListener('click', onClickFn, true);

1 DIV 1
2 P 1

div p



document

1 attachEvent(eventType, handler)

73
1 detachEvent(eventType, handler)

1 var btn = document.getElementById('.btn');


2 btn.attachEvent(‘onclick’, showMessage);
3 btn.detachEvent(‘onclick’, showMessage);




click keydown

74
DOM



1 <ul id="list">
2 <li>item 1</li>
3 <li>item 2</li>
4 <li>item 3</li>
5 ......
6 <li>item n</li>
7 </ul>

1 //
2 const lis = document.getElementsByTagName("li")
3 //
4 for (let i = 0; i < lis.length; i++) {
5 lis[i].onclick = function(e){
6 console.log(e.target.innerHTML)
7 }
8 }

ul

75
1 //
2 document.getElementById('list').addEventListener('click', function (e) {
3 //
4 var event = e || window.event;
5 var target = event.target || event.srcElement;
6 //
7 if (target.nodeName.toLocaleLowerCase === 'li') {
8 console.log('the content is: ', target.innerHTML);
9 }
10 });

html input

1 <input type="button" name="" id="btn" value=" " />


2 <ul id="ul1">
3 <li>item 1</li>
4 <li>item 2</li>
5 <li>item 3</li>
6 <li>item 4</li>
7 </ul>

76
1 const oBtn = document.getElementById("btn");
2 const oUl = document.getElementById("ul1");
3 const num = 4;
4
5 //
6 oUl.onclick = function (ev) {
7 ev = ev || window.event;
8 const target = ev.target || ev.srcElement;
9 if (target.nodeName.toLowerCase() == 'li') {
10 console.log('the content is: ', target.innerHTML);
11 }
12
13 };
14
15 //
16 oBtn.onclick = function () {
17 num++;
18 const oLi = document.createElement('li');
19 oLi.innerHTML = `item ${num}`;
20 oUl.appendChild(oLi);
21 };


click mousedown mouseup keydown keyup keypre
ss

focus blur

mousemove mouseout

77




JavaScript

1 function init() {
2 var name = "Mozilla"; // name init
3 function displayName() { // displayName()
4 alert(name); //
5 }
6 displayName();
7 }
8 init();

displayName()



78
1 function makeSizer(size) {
2 return function() {
3 document.body.style.fontSize = size + 'px';
4 };
5 }
6
7 var size12 = makeSizer(12);
8 var size14 = makeSizer(14);
9 var size16 = makeSizer(16);
10
11 document.getElementById('size-12').onclick = size12;
12 document.getElementById('size-14').onclick = size14;
13 document.getElementById('size-16').onclick = size16;



79
1 //
2 function getArea(width, height) {
3 return width * height
4 }
5 // 10
6 const area1 = getArea(10, 20)
7 const area2 = getArea(10, 30)
8 const area3 = getArea(10, 40)
9
10 //
11 function getArea(width) {
12 return height => {
13 return width * height
14 }
15 }
16
17 const getTenWidthArea = getArea(10)
18 // 10
19 const area1 = getTenWidthArea(20)
20
21 //
22 const getTwentyWidthArea = getArea(20)



JavaScript

80
1 var Counter = (function() {
2 var privateCounter = 0;
3 function changeBy(val) {
4 privateCounter += val;
5 }
6 return {
7 increment: function() {
8 changeBy(1);
9 },
10 decrement: function() {
11 changeBy(-1);
12 },
13 value: function() {
14 return privateCounter;
15 }
16 }
17 })();
18
19 var Counter1 = makeCounter();
20 var Counter2 = makeCounter();
21 console.log(Counter1.value()); /* logs 0 */
22 Counter1.increment();
23 Counter1.increment();
24 console.log(Counter1.value()); /* logs 2 */
25 Counter1.decrement();
26 console.log(Counter1.value()); /* logs 1 */
27 console.log(Counter2.value()); /* logs 0 */

Counter1 Counter2





81
1 function MyObject(name, message) {
2 this.name = name.toString();
3 this.message = message.toString();
4 this.getName = function() {
5 return this.name;
6 };
7
8 this.getMessage = function() {
9 return this.message;
10 };
11 }

1 function MyObject(name, message) {


2 this.name = name.toString();
3 this.message = message.toString();
4 }
5 MyObject.prototype.getName = function() {
6 return this.name;
7 };
8 MyObject.prototype.getMessage = function() {
9 return this.message;
10 };



82

JS undefined null boolean string n
umber symbol object

1 let x = y ? 1 : a;



83


84
1 Number(324) // 324
2
3 //
4 Number('324') // 324
5
6 // NaN
7 Number('324abc') // NaN
8
9 // 0
10 Number('') // 0
11
12 // true 1 false 0
13 Number(true) // 1
14 Number(false) // 0
15
16 // undefined NaN
17 Number(undefined) // NaN
18
19 // null 0
20 Number(null) // 0
21
22 // NaN( )
23 Number({a: 1}) // NaN
24 Number([1, 2, 3]) // NaN
25 Number([5]) // 5

Number
NaN



parseInt Number parseInt

1 parseInt('32a3') //32



85
1 //
2 String(1) // "1"
3
4 //
5 String("a") // "a"
6
7 // true "true" false "false"
8 String(true) // "true"
9
10 //undefined "undefined"
11 String(undefined) // "undefined"
12
13 //null "null"
14 String(null) // "null"
15
16 //
17 String({a: 1}) // "[object Object]"
18 String([1, 2, 3]) // "1,2,3"



86
1 Boolean(undefined) // false
2 Boolean(null) // false
3 Boolean(0) // false
4 Boolean(NaN) // false
5 Boolean('') // false
6 Boolean({}) // true
7 Boolean([]) // true
8 Boolean(new Boolean(false)) // true



== != > < if while

+ - * / %



Boolean

87
false true



1 '5' + 1 // '51'
2 '5' + true // "5true"
3 '5' + false // "5false"
4 '5' + {} // "5[object Object]"
5 '5' + [] // "5"
6 '5' + function (){} // "5function (){}"
7 '5' + undefined // "5undefined"
8 '5' + null // "5null"



1 '5' - '2' // 3
2 '5' * '2' // 10
3 true - 1 // 0
4 false - 1 // -1
5 '1' - 1 // 0
6 '5' * [] // 0
7 false / '5' // 0
8 'abc' - 1 // NaN
9 null + 1 // 1
10 undefined + 1 // NaN

null 0 undefined NaN

88



JavaScript



89
1 function shallowClone(obj) {
2 const newObj = {};
3 for(let prop in obj) {
4 if(obj.hasOwnProperty(prop)){
5 newObj[prop] = obj[prop];
6 }
7 }
8 return newObj;
9 }

JavaScript

Object.assign

Array.prototype.slice() Array.prototype.concat()



1 var obj = {
2 age: 18,
3 nature: ['smart', 'good'],
4 names: {
5 name1: 'fx',
6 name2: 'xka'
7 },
8 love: function () {
9 console.log('fx is a great girl')
10 }
11 }
12 var newObj = Object.assign({}, fxObj);



90
1 const fxArr = ["One", "Two", "Three"]
2 const fxArrs = fxArr.slice(0)
3 fxArrs[1] = "love";
4 console.log(fxArr) // ["One", "Two", "Three"]
5 console.log(fxArrs) // ["One", "love", "Three"]



1 const fxArr = ["One", "Two", "Three"]


2 const fxArrs = fxArr.concat()
3 fxArrs[1] = "love";
4 console.log(fxArr) // ["One", "Two", "Three"]
5 console.log(fxArrs) // ["One", "love", "Three"]



1 const fxArr = ["One", "Two", "Three"]


2 const fxArrs = [...fxArr]
3 fxArrs[1] = "love";
4 console.log(fxArr) // ["One", "Two", "Three"]
5 console.log(fxArrs) // ["One", "love", "Three"]



91


1 const _ = require('lodash');
2 const obj1 = {
3 a: 1,
4 b: { f: { g: 1 } },
5 c: [1, 2, 3]
6 };
7 const obj2 = _.cloneDeep(obj1);
8 console.log(obj1.b.f === obj2.b.f);// false



1 const $ = require('jquery');
2 const obj1 = {
3 a: 1,
4 b: { f: { g: 1 } },
5 c: [1, 2, 3]
6 };
7 const obj2 = $.extend(true, {}, obj1);
8 console.log(obj1.b.f === obj2.b.f); // false



1 const obj2=JSON.parse(JSON.stringify(obj1));

undefined symbol

92
1 const obj = {
2 name: 'A',
3 name1: undefined,
4 name3: function() {},
5 name4: Symbol('A')
6 }
7 const obj2 = JSON.parse(JSON.stringify(obj));
8 console.log(obj2); // {name: "A"}



1 function deepClone(obj, hash = new WeakMap()) {


2 if (obj === null) return obj; // null undefined
3 if (obj instanceof Date) return new Date(obj);
4 if (obj instanceof RegExp) return new RegExp(obj);
5 //
6 if (typeof obj !== "object") return obj;
7 //
8 if (hash.get(obj)) return hash.get(obj);
9 let cloneObj = new obj.constructor();
10 // constructor, constructor
11 hash.set(obj, cloneObj);
12 for (let key in obj) {
13 if (obj.hasOwnProperty(key)) {
14 //
15 cloneObj[key] = deepClone(obj[key], hash);
16 }
17 }
18 return cloneObj;
19 }



93
94
1 //
2 const obj1 = {
3 name : 'init',
4 arr : [1,[2,3],4],
5 };
6 const obj3=shallowClone(obj1) //
7 obj3.name = "update";
8 obj3.arr[1] = [5,6,7] ; //
9
10 console.log('obj1',obj1) // obj1 { name: 'init', arr: [ 1, [ 5, 6, 7 ],
4 ] }
11 console.log('obj3',obj3) // obj3 { name: 'update', arr: [ 1, [ 5, 6, 7 ],
4 ] }

1 //
2 const obj1 = {
3 name : 'init',
4 arr : [1,[2,3],4],
5 };
6 const obj4=deepClone(obj1) //
7 obj4.name = "update";
8 obj4.arr[1] = [5,6,7] ; //
9
10 console.log('obj1',obj1) // obj1 { name: 'init', arr: [ 1, [ 2, 3 ], 4 ] }
11 console.log('obj4',obj4) // obj4 { name: 'update', arr: [ 1, [ 5, 6, 7 ],
4 ] }





95


1 const add = (a,b) => a+b;


2 const calc = memoize(add); //
3 calc(10,20);// 30
4 calc(10,20);// 30





96
1 (function() {
2 var a = 1;
3 function add() {
4 const b = 2
5 let sum = b + a
6 console.log(sum); // 3
7 }
8 add()
9 })()

add a = 1



1 //
2 var add = function (x,y) {
3 return x+y;
4 }
5 add(3,4) //7
6
7 //
8 var add2 = function (x) {
9 //** **
10 return function (y) {
11 return x+y;
12 }
13 }
14 add2(3)(4) //7



97
1 function foo(){
2 var a = 2;
3
4 function bar() {
5 console.log(a);
6 }
7 return bar;
8 }
9 var baz = foo();
10 baz();//2

foo bar baz foo bar


a

1 const memoize = function (func, content) {


2 let cache = Object.create(null)
3 content = content || this
4 return (...key) => {
5 if (!cache[key]) {
6 cache[key] = func.apply(content, key)
7 }
8 return cache[key]
9 }
10 }

1 const calc = memoize(add);


2 const num1 = calc(100,200)
3 const num2 = calc(100,200) //

cache

98
cache cache
func cache



 

 

 

+ ${} concat

99
 

1 let stringValue = "hello ";


2 let result = stringValue.concat("world");
3 console.log(result); // "hello world"
4 console.log(stringValue); // "hello"

 

1 let stringValue = "hello world";


2 console.log(stringValue.slice(3)); // "lo world"
3 console.log(stringValue.substring(3)); // "lo world"
4 console.log(stringValue.substr(3)); // "lo world"
5 console.log(stringValue.slice(3, 7)); // "lo w"
6 console.log(stringValue.substring(3,7)); // "lo w"
7 console.log(stringValue.substr(3, 7)); // "lo worl"

 

100
 

1 let stringValue = " hello world ";


2 let trimmedStringValue = stringValue.trim();
3 console.log(stringValue); // " hello world "
4 console.log(trimmedStringValue); // "hello world"

 

1 let stringValue = "na ";


2 let copyResult = stringValue.repeat(2) // na na

 

1 let stringValue = "foo";


2 console.log(stringValue.padStart(6)); // " foo"
3 console.log(stringValue.padStart(9, ".")); // "......foo"

 

1 let stringValue = "hello world";


2 console.log(stringValue.toUpperCase()); // "HELLO WORLD"
3 console.log(stringValue.toLowerCase()); // "hello world"

 

101
 

1 let message = "abcde";


2 console.log(message.charAt(2)); // "c"

 

1 let stringValue = "hello world";


2 console.log(stringValue.indexOf("o")); // 4

 

1 let message = "foobarbaz";


2 console.log(message.startsWith("foo")); // true
3 console.log(message.startsWith("bar")); // false
4 console.log(message.includes("bar")); // true
5 console.log(message.includes("qux")); // false

 

 

102
1 let str = "12+23+34"
2 let arr = str.split("+") // [12,23,34]

 

 

RegExp

1 let text = "cat, bat, sat, fat";


2 let pattern = /.at/;
3 let matches = text.match(pattern);
4 console.log(matches[0]); // "cat"

 

RegExp

1 let text = "cat, bat, sat, fat";


2 let pos = text.search(/at/);
3 console.log(pos); // 1

 

103
1 let text = "cat, bat, sat, fat";
2 let result = text.replace("at", "ond");
3 console.log(result); // "cond, bat, sat, fat"









104
push()

1 let colors = []; //


2 let count = colors.push("red", "green"); //
3 console.log(count) // 2



1 let colors = new Array(); //


2 let count = colors.unshift("red", "green"); //
3 alert(count); // 2



1 let colors = ["red", "green", "blue"];


2 let removed = colors.splice(1, 0, "yellow", "orange")
3 console.log(colors) // red,yellow,orange,green,blue
4 console.log(removed) // []



1 let colors = ["red", "green", "blue"];


2 let colors2 = colors.concat("yellow", ["black", "brown"]);
3 console.log(colors); // ["red", "green","blue"]
4 console.log(colors2); // ["red", "green", "blue", "yellow", "black", "brow
n"]

105




pop() length

1 let colors = ["red", "green"]


2 let item = colors.pop(); //
3 console.log(item) // green
4 console.log(colors.length) // 1



shift() length

1 let colors = ["red", "green"]


2 let item = colors.shift(); //
3 console.log(item) // red
4 console.log(colors.length) // 1



1 let colors = ["red", "green", "blue"];


2 let removed = colors.splice(0,1); //
3 console.log(colors); // green,blue
4 console.log(removed); // red

106


1 let colors = ["red", "green", "blue", "yellow", "purple"];


2 let colors2 = colors.slice(1);
3 let colors3 = colors.slice(1, 4);
4 console.log(colors) // red,green,blue,yellow,purple
5 concole.log(colors2); // green,blue,yellow,purple
6 concole.log(colors3); // green,blue,yellow



splice



1 let colors = ["red", "green", "blue"];


2 let removed = colors.splice(1, 1, "red", "purple"); //
3 console.log(colors); // red,red,purple,blue
4 console.log(removed); // green





107
1 let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
2 numbers.indexOf(4) // 3



true false

1 let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];


2 numbers.includes(4) // true



1 const people = [
2 {
3 name: "Matt",
4 age: 27
5 },
6 {
7 name: "Nicholas",
8 age: 29
9 }
10 ];
11 people.find((element, index, array) => element.age < 28) // // {name: "Mat
t", age: 27}





108
1 let values = [1, 2, 3, 4, 5];
2 values.reverse();
3 alert(values); // 5,4,3,2,1



1 function compare(value1, value2) {


2 if (value1 < value2) {
3 return -1;
4 } else if (value1 > value2) {
5 return 1;
6 } else {
7 return 0;
8 }
9 }
10 let values = [0, 1, 5, 10, 15];
11 values.sort(compare);
12 alert(values); // 0,1,5,10,15





1 let colors = ["red", "green", "blue"];


2 alert(colors.join(",")); // red,green,blue
3 alert(colors.join("||")); // red||green||blue

109




1 let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];


2 let someResult = numbers.some((item, index, array) => item > 2);
3 console.log(someResult) // true



1 let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];


2 let everyResult = numbers.every((item, index, array) => item > 2);
3 console.log(everyResult) // false



1 let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];


2 numbers.forEach((item, index, array) => {
3 //
4 });

110


true

1 let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];


2 let filterResult = numbers.filter((item, index, array) => item > 2);
3 console.log(filterResult); // 3,4,5,4,3



1 let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];


2 let mapResult = numbers.map((item, index, array) => item * 2);
3 console.log(mapResult) // 2,4,6,8,10,8,6,4,2





111
JavaScript

JavaScript

ajax setTimeout

112


1 console.log(1)
2
3 setTimeout(()=>{
4 console.log(2)
5 }, 0)
6
7 new Promise((resolve, reject)=>{
8 console.log('new Promise')
9 resolve()
10 }).then(()=>{
11 console.log('then')
12 })
13
14 console.log(3)

console.log(1)

setTimeout() Event Table console.log(2)


Event Queue

new Promise

.then Event Table

console.log(3)

1 'new Promise' 3 2 'then'

1 'new Promise' 3 'then' 2

setTimeout .then



113


114
115
1 console.log(1)
2 setTimeout(()=>{
3 console.log(2)
4 }, 0)
5 new Promise((resolve, reject)=>{
6 console.log('new Promise')
7 resolve()
8 }).then(()=>{
9 console.log('then')
10 })
11 console.log(3)

1 // console.log(1) 1
2 //
3 // new Promise 'new Promise'
4 // .then
5 // console.log(3) 3
6 // .then
'then'
7 // 2


async await async wait async
await



async promise

116
1 function f() {
2 return Promise.resolve('TEST');
3 }
4
5 // asyncF is equivalent to f!
6 async function asyncF() {
7 return 'TEST';
8 }



await Promise Promise

1 async function f(){


2 //
3 // return 123
4 return await 123
5 }
6 f().then(v => console.log(v)) // 123

await await

1 async function fn1 (){


2 console.log(1)
3 await fn2()
4 console.log(2) //
5 }
6
7 async function fn2 (){
8 console.log('fn2')
9 }
10
11 fn1()
12 console.log(3)

await async
async

117
1 fn2 3 2


JavaScript

1 async function async1() {


2 console.log('async1 start')
3 await async2()
4 console.log('async1 end')
5 }
6 async function async2() {
7 console.log('async2')
8 }
9 console.log('script start')
10 setTimeout(function () {
11 console.log('settimeout')
12 })
13 async1()
14 new Promise(function (resolve) {
15 console.log('promise1')
16 resolve()
17 }).then(function () {
18 console.log('promise2')
19 })
20 console.log('script end')

 console.log('script start') script star


t



 async1() async1 async1 start await


async2 async2

 new Promise promise1 .then()

 script end await


async1 end

118
 then promise2

 settimeout

script start async1 start async2 promise1 script e


nd async1 end promise2 settimeout




javaScript



Cookie
HTTP

cookie

119
cookie HTTPS
cookie cookie
cookie

cookie

1 Expires=Wed, 21 Oct 2015 07:28:00 GMT

Expires

1 Max-Age=604800

Domain Cookie

Path URL Cookie

1 Path=/docs # /docs/Web/ Cookie

Secure Cookie HTTPS

cookie cookie

cookie

1 document.cookie = ' = ';

cookie domain path


cookie

1 Set-Cookie:name=aa; domain=aa.net; path=/ #


2 document.cookie =name=bb; domain=aa.net; path=/ #

120
cookie cookie cookie



HTML5



localStorage storage
storage

localStorage

localStorage

1 localStorage.setItem('username','cfangxu');

1 localStorage.getItem('username')

1 localStorage.key(0) //

121
1 localStorage.removeItem('username')

1 localStorage.clear()

localStorage

Cookie

1 localStorage.setItem('key', {name: 'value'});


2 console.log(localStorage.getItem('key')); // '[object, Object]'



sessionStorage localStorage
sessionStorage



indexedDB

Web Storage
IndexedDB



LocalStorage

JS

122


indexedDB

object store

DOM

request

indexdb Godb.js


cookie sessionStorage localStorage

cookie 4k sessionStorage localStorage


cookie

localStorage ses
sionStorage cookie cookie

cookie coo
kie sessionStorage localStorage



cookie

localStorage

sessionStorage

indexedDB

123






124












125
1 const input = document.querySelector('input');
2 input.addEventListener('change', function() {
3 var file = this.files[0];
4 });

md5

1 const md5code = md5(file);

126
1 var reader = new FileReader();
2 reader.readAsArrayBuffer(file);
3 reader.addEventListener("load", function(e) {
4 // 10M ,
5 var slice = e.target.result.slice(0, 10*1024*1024);
6 });

1 const formdata = new FormData();


2 formdata.append('0', slice);
3 //
4 formdata.append('filename', file.filename);
5 var xhr = new XMLHttpRequest();
6 xhr.addEventListener('load', function() {
7 //xhr.responseText
8 });
9 xhr.open('POST', '');
10 xhr.send(formdata);
11 xhr.addEventListener('progress', updateProgress);
12 xhr.upload.addEventListener('progress', updateProgress);
13
14 function updateProgress(event) {
15 if (event.lengthComputable) {
16 //
17 }
18 }

127
1 function checkFileType(type, file, back) {
2 /**
3 * type png jpg mp4 ...
4 * file input.change=> this.files[0]
5 * back callback(boolean)
6 */
7 var args = arguments;
8 if (args.length != 3) {
9 back(0);
10 }
11 var type = args[0]; // type = '(png|jpg)' , 'png'
12 var file = args[1];
13 var back = typeof args[2] == 'function' ? args[2] : function() {};
14 if (file.type == '') {
15 //
16 var imgType = [
17 'ff d8 ff', //jpg
18 '89 50 4e', //png
19
20 '0 0 0 14 66 74 79 70 69 73 6F 6D', //mp4
21 '0 0 0 18 66 74 79 70 33 67 70 35', //mp4
22 '0 0 0 0 66 74 79 70 33 67 70 35', //mp4
23 '0 0 0 0 66 74 79 70 4D 53 4E 56', //mp4
24 '0 0 0 0 66 74 79 70 69 73 6F 6D', //mp4
25
26 '0 0 0 18 66 74 79 70 6D 70 34 32', //m4v
27 '0 0 0 0 66 74 79 70 6D 70 34 32', //m4v
28
29 '0 0 0 14 66 74 79 70 71 74 20 20', //mov
30 '0 0 0 0 66 74 79 70 71 74 20 20', //mov
31 '0 0 0 0 6D 6F 6F 76', //mov
32
33 '4F 67 67 53 0 02', //ogg
34 '1A 45 DF A3', //ogg
35
36 '52 49 46 46 x x x x 41 56 49 20', //avi (RIFF fileSize fileTy
pe LIST)(52 49 46 46,DC 6C 57 09,41 56 49 20,4C 49 53 54)
37 ];
38 var typeName = [
39 'jpg',
40 'png',
41 'mp4',
42 'mp4',
43 'mp4',
44 'mp4',

128
45 'mp4',
46
'm4v',
47
'm4v',
48
'mov',
49
'mov',
50
'mov',
51
'ogg',
52
'ogg',
53
'avi',
54
];
55
var sliceSize = /png|jpg|jpeg/.test(type) ? 3 : 12;
56
var reader = new FileReader();
57
reader.readAsArrayBuffer(file);
58
reader.addEventListener("load", function(e) {
59
var slice = e.target.result.slice(0, sliceSize);
60
reader = null;
61
if (slice && slice.byteLength == sliceSize) {
62
var view = new Uint8Array(slice);
63
var arr = [];
64
view.forEach(function(v) {
65
arr.push(v.toString(16));
66
});
67
view = null;
68
var idx = arr.join(' ').indexOf(imgType);
69
if (idx > -1) {
70
back(typeName[idx]);
71
} else {
72
arr = arr.map(function(v) {
73
if (i > 3 && i < 8) {
74
return 'x';
75
}
76
return v;
77
});
78
var idx = arr.join(' ').indexOf(imgType);
79
if (idx > -1) {
80
back(typeName[idx]);
81
} else {
82
back(false);
83
}
84
85
}
86
} else {
87
back(false);
88
}
89
90
});
91
} else {
92
var type = file.name.match(/\.(\w+)$/)[1];

129
93 back(type);
94
}
95
}

1 checkFileType('(mov|mp4|avi)',file,function(fileType){
2 // fileType = mp4,
3 // file false
4 });

1 formdata.append('filename', md5code+'.'+fileType);

md5

XMLHttpRequest abort





130



AJAX

JavaScript XML

Ajax XmlHttpRequest
JavaScript DOM

131
Ajax XMLHttpRequest

HTTP XHR


Ajax

Ajax XMLHttpRequest

XMLHttpRequest open()

XMLHttpRequest send()
XMLHttpRequest onreadystatechange

HTML

132


XMLHttpRequest() XMLHttpRequest

1 const xhr = new XMLHttpRequest();



XMLHttpRequest open()

1 xhr.open(method, url, [async][, user][, password])

method GET POST

url

async true

user

password



XMLHttpRequest send()

1 xhr.send([body])

body XHR null

GET

open() url

send() null



133
onreadystatechange XMLHttpRequest.
readyState

XMLHttpRequest.readyState

readyState readystatechange

XMLHttpRequest.responseText

1 const request = new XMLHttpRequest()


2 request.onreadystatechange = function(e){
3 if(request.readyState === 4){ //
4 if(request.status >= 200 && request.status <= 300){
5 console.log(request.responseText) //
6 }else if(request.status >=400){
7 console.log(" " + request.status)
8 }
9 }
10 }
11 request.open('POST','http://xxxx')
12 request.send()


XMLHttpRequest ajax

134
1 // ajax
2 function ajax(options) {
3 // XMLHttpRequest
4 const xhr = new XMLHttpRequest()
5
6
7 //
8 options = options || {}
9 options.type = (options.type || 'GET').toUpperCase()
10 options.dataType = options.dataType || 'json'
11 const params = options.data
12
13 //
14 if (options.type === 'GET') {
15 xhr.open('GET', options.url + '?' + params, true)
16 xhr.send(null)
17 } else if (options.type === 'POST') {
18 xhr.open('POST', options.url, true)
19 xhr.send(params)
20
21 //
22 xhr.onreadystatechange = function () {
23 if (xhr.readyState === 4) {
24 let status = xhr.status
25 if (status >= 200 && status < 300) {
26 options.success && options.success(xhr.responseText, xhr.r
esponseXML)
27 } else {
28 options.fail && options.fail(status)
29 }
30 }
31 }
32 }

135
1 ajax({
2 type: 'post',
3 dataType: 'json',
4 data: {},
5 url: 'https://xxxx',
6 success: function(text,xml){//
7 console.log(text)
8 },
9 fail: function(status){////
10 console.log(status)
11 }
12 })





resize scroll keypress mousemove



136
debounce throttle





1 function throttled1(fn, delay = 500) {


2 let oldtime = Date.now()
3 return function (...args) {
4 let newtime = Date.now()
5 if (newtime - oldtime >= delay) {
6 fn.apply(null, args)
7 oldtime = Date.now()
8 }
9 }
10 }

delay

137
1 function throttled2(fn, delay = 500) {
2 let timer = null
3 return function (...args) {
4 if (!timer) {
5 timer = setTimeout(() => {
6 fn.apply(this, args)
7 timer = null
8 }, delay);
9 }
10 }
11 }

1 function throttled(fn, delay) {


2 let timer = null
3 let starttime = Date.now()
4 return function () {
5 let curTime = Date.now() //
6 let remaining = delay - (curTime - starttime) //

7 let context = this


8 let args = arguments
9 clearTimeout(timer)
10 if (remaining <= 0) {
11 fn.apply(context, args)
12 starttime = Date.now()
13 } else {
14 timer = setTimeout(fn, remaining);
15 }
16 }
17 }



138
1 function debounce(func, wait) {
2 let timeout;
3
4 return function () {
5 let context = this; // this
6 let args = arguments; // event
7
8 clearTimeout(timeout)
9 timeout = setTimeout(function(){
10 func.apply(context, args)
11 }, wait);
12 }
13 }

1 function debounce(func, wait, immediate) {


2
3 let timeout;
4
5 return function () {
6 let context = this;
7 let args = arguments;
8
9 if (timeout) clearTimeout(timeout); // timeout null
10 if (immediate) {
11 let callNow = !timeout; //

12 timeout = setTimeout(function () {
13 timeout = null;
14 }, wait)
15 if (callNow) {
16 func.apply(context, args)
17 }
18 }
19 else {
20 timeout = setTimeout(function () {
21 func.apply(context, args)
22 }, wait);
23 }
24 }
25 }

139


setTimeout

clearTimeout setTimeout



140
resize





141




142
offsetTop offset

clientWidth clientHeight

clientWidth clientWidth = content + pad


ding

clientHeight clientHeight = content + p


adding

client

scroll

scrollWidth scrollHeight

scrollLeft scrollTop

scrollTop > 0

scrollLeft > 0

scrollLeft scrollTop



143
1 el.offsetTop - document.documentElement.scrollTop <= viewPortHeight

1 function isInViewPortOfOne (el) {


2 // viewPortHeight
3 const viewPortHeight = window.innerHeight || document.documentElement.c
lientHeight || document.body.clientHeight
4 const offsetTop = el.offsetTop
5 const scrollTop = document.documentElement.scrollTop
6 const top = offsetTop - scrollTop
7 return top <= viewPortHeight
8 }



DOMRect left top right bottom x y width h


eight

1 const target = document.querySelector('.target');


2 const clientRect = target.getBoundingClientRect();
3 console.log(clientRect);
4
5 // {
6 // bottom: 556.21875,
7 // height: 393.59375,
8 // left: 333,
9 // right: 1017,
10 // top: 162.625,
11 // width: 684
12 // }

144
top left

145
1 function isInViewPort(element) {
2 const viewWidth = window.innerWidth || document.documentElement.clientWi
dth;
3 const viewHeight = window.innerHeight || document.documentElement.client
Height;
4 const {
5 top,
6 right,
7 bottom,
8 left,
9 } = element.getBoundingClientRect();
10
11 return (
12 top >= 0 &&
13 left >= 0 &&
14 right <= viewWidth &&
15 bottom <= viewHeight
16 );
17 }



Intersection Observer
getBoundingClientRect



1 const options = {
2 // 0 - 1
3 // 1
4 threshold: 1.0,
5 root:document.querySelector('#scrollArea') //
6 };
7
8 const callback = (entries, observer) => { ....}
9
10 const observer = new IntersectionObserver(callback, options);

146
new IntersectionObserver observer callback
threshold

callback

1 // callback
2 const callback = function(entries, observer) {
3 entries.forEach(entry => {
4 entry.time; //
5 entry.rootBounds; //
6 entry.boundingClientRect; //
7 entry.intersectionRect; //
8 entry.intersectionRatio; //

9 entry.target; //
10 });
11 };



observer.observe(target)

1 const target = document.querySelector('.target');


2 observer.observe(target);



Html

1 <div class="container"></div>

css

147
1 .container {
2 display: flex;
3 flex-wrap: wrap;
4 }
5 .target {
6 margin: 5px;
7 width: 20px;
8 height: 20px;
9 background: red;
10 }

container

1 const $container = $(".container");


2
3 // 100000 <div class="target"></div>
4 function createTargets() {
5 const htmlString = new Array(100000)
6 .fill('<div class="target"></div>')
7 .join("");
8 $container.html(htmlString);
9 }

getBoundingClientRect

1 function isInViewPort(element) {
2 const viewWidth = window.innerWidth || document.documentElement.clientW
idth;
3 const viewHeight =
4 window.innerHeight || document.documentElement.clientHeight;
5 const { top, right, bottom, left } = element.getBoundingClientRect();
6
7 return top >= 0 && left >= 0 && right <= viewWidth && bottom <= viewHei
ght;
8 }

scroll
yellow

148
1 $(window).on("scroll", () => {
2 console.log("scroll !");
3 $targets.each((index, element) => {
4 if (isInViewPort(element)) {
5 $(element).css("background-color", "yellow");
6 }
7 });
8 });

scroll scroll

Intersection Observer

1 const observer = new IntersectionObserver(getYellow, { threshold: 1.0 });

getYellow

1 function getYellow(entries, observer) {


2 entries.forEach(entry => {
3 $(entry.target).css("background-color", "yellow");
4 });
5 }

.target

1 $targets.each((index, element) => {


2 observer.observe(element);
3 });



149


passport

passport
passport
passport

Application1 Application2 Application3 SSO


Application1 Application2 Application3 SSO SSO



150




cookie domain cookie path


web

Cookie Cookie domain


Cookie path Session ID Token
Cookie

tieba.baidu.com map.baid
u.com baidu.com



Cookie
Web

token Coo
kie Cookie

Token

Cookie Cookie

URL
Token URL

Token Token
Token Cookie
Cookie Token

151


Session ID Token LocalStorage


LocalStorage

Session ID Token

Session ID Token L
ocalStorage LocalStorage

1 // token
2 var token = result.data.token;
3
4 // iframe iframe HTML
5 var iframe = document.createElement("iframe");
6 iframe.src = "http://app1.com/localstorage.html";
7 document.body.append(iframe);
8 // postMessage() token iframe
9 setTimeout(function () {
10 iframe.contentWindow.postMessage(token, "http://app1.com");
11 }, 4000);
12 setTimeout(function () {
13 iframe.remove();
14 }, 6000);
15
16 // iframe HTML token
localStorage
17 window.addEventListener('message', function (event) {
18 localStorage.setItem('token', event.data)
19 }, false);

iframe postMessage() Token LocalSto


rage LocalStorage Token
Token



152
153
sso sso

sso





154
iscroll better-scroll pulltorefresh.js





scrollTop window

155
clientHeight

scrollHeight
body

1 scrollTop + clientHeight >= scrollHeight

1 let clientHeight = document.documentElement.clientHeight; //


2 let scrollHeight = document.body.scrollHeight;
3 let scrollTop = document.documentElement.scrollTop;
4
5 let distance = 50; // 50
6
7 if ((scrollTop + clientHeight) >= (scrollHeight - distance)) {
8 console.log(" ");
9 }



touchstart e.touches[0].pageY

touchmove 0
translateY

touchend callback transla


teY 0

Html

156
1 <main>
2 <p class="refreshText"></p >
3 <ul id="refreshContainer">
4 <li>111</li>
5 <li>222</li>
6 <li>333</li>
7 <li>444</li>
8 <li>555</li>
9 ...
10 </ul>
11 </main>

touchstart

1 var _element = document.getElementById('refreshContainer'),


2 _refreshText = document.querySelector('.refreshText'),
3 _startPos = 0, //
4 _transitionHeight = 0; //
5
6 _element.addEventListener('touchstart', function(e) {
7 _startPos = e.touches[0].pageY; //
8 _element.style.position = 'relative';
9 _element.style.transition = 'transform 0s';
10 }, false);

touchmove

1 _element.addEventListener('touchmove', function(e) {
2 // e.touches[0].pageY
3 _transitionHeight = e.touches[0].pageY - _startPos; //
4
5 if (_transitionHeight > 0 && _transitionHeight < 60) {
6 _refreshText.innerText = ' ';
7 _element.style.transform = 'translateY('+_transitionHeight+'px)';
8
9 if (_transitionHeight > 55) {
10 _refreshText.innerText = ' ';
11 }
12 }
13 }, false);

157
touchend

1 _element.addEventListener('touchend', function(e) {
2 _element.style.transition = 'transform 0.5s ease 1s';
3 _element.style.transform = 'translateY(0px)';
4 _refreshText.innerText = ' ...';
5 // todo...
6
7 }, false);


better-scroll

1 <div id="position-wrapper">
2 <div>
3 <p class="refresh"> </p >
4 <div class="position-list">
5 <!-- -->
6 </div>
7 <p class="more"> </p >
8 </div>
9 </div>

use

158
1 import BScroll from "@better-scroll/core";
2 import PullDown from "@better-scroll/pull-down";
3 import PullUp from '@better-scroll/pull-up';
4 BScroll.use(PullDown);
5 BScroll.use(PullUp);

BetterScroll

159
1 let pageNo = 1,pageSize = 10,dataList = [],isMore = true;
2 var scroll= new BScroll("#position-wrapper",{
3 scrollY:true,//
4 click:true,// click true
5 pullUpLoad:true,//
6 pullDownRefresh:{
7 threshold:50,// pullingDown
8 stop:0//
9 }
10 });
11 //
12 scroll.on("pullingDown",pullingDownHandler);
13 //
14 scroll.on("scroll",scrollHandler);
15 //
16 scroll.on("pullingUp",pullingUpHandler);
17
18 async function pullingDownHandler(){
19 dataList=[];
20 pageNo=1;
21 isMore=true;
22 $(".more").text(" ");
23 await getlist();//
24 scroll.finishPullDown();//
25 scroll.refresh();// dom
26 }
27 async function pullingUpHandler(){
28 if(!isMore){
29 $(".more").text(" ");
30 scroll.finishPullUp();//
31 return;
32 }
33 pageNo++;
34 await this.getlist();//
35 scroll.finishPullUp();//
36 scroll.refresh();// dom
37 }
38 function scrollHandler(){
39 if(this.y>50) $('.refresh').text(" ");
40 else $('.refresh').text(" ");
41 }
42 function getlist(){
43 //
44 let result=....;
45 dataList=dataList.concat(result);

160
46 //
47
if(result.length<pageSize) isMore=false;
48
// dataList html
49
}

better-scroll

wrapper

wrapper

DOM DOM new BScroll


()

DOM refresh()

finishPullUp() finishPullDown()

better-scroll click
click:true



 

161
 

JavaScript



1 const re = /\d+/g;

 RegExp

1 const re = new RegExp("\\d+","g");


2
3 const rul = "\\d+"
4 const re1 = new RegExp(rul,"g");

\ \\

 

162
{1,}

{0,1}

163
 

s .

u unicode

y sticky

164
1 var re = /pattern/flags;
2 var re = new RegExp("pattern", "flags");

 

1 const reg = /ab{1,3}c/

bbb
b bb

1 const string = "12345";


2 const regx = /(\d{1,3})(\d{1,3})/;
3 console.log( string.match(reg) );
4 // => ["12345", "123", "45", index: 0, input: "12345"]

\d{1,3} \d{1,3}

 

1 var string = "12345";


2 var regex = /(\d{1,3}?)(\d{1,3})/;
3 console.log( string.match(regex) );
4 // => ["1234", "1", "234", index: 0, input: "12345"]

\d{1,3}? \d{1,3}

 

165
() beyond{3} d (beyond){3} b
eyond

() | (abc | xxx) abc xxx

1 let str = "John Smith";


2
3 //
4 console.log(str.replace(/(john) (smith)/i, '$2, $1')) // Smith, John

 

match matchAll search replace split

test exec

166
String

 

str.match(regexp) str regexp

regexp g
index input str

1 let str = "I love JavaScript";


2
3 let result = str.match(/Java(Script)/);
4
5 console.log( result[0] ); // JavaScript
6 console.log( result[1] ); // Script
7 console.log( result.length ); // 2
8
9 //
10 console.log( result.index ); // 7
11 console.log( result.input ); // I love JavaScript

regexp g

1 let str = "I love JavaScript";


2
3 let result = str.match(/Java(Script)/g);
4
5 console.log( result[0] ); // JavaScript
6 console.log( result.length ); // 1

g null

167
1 let str = "I love JavaScript";
2
3 let result = str.match(/HTML/);
4
5 console.log(result); // null

 

1 const regexp = /t(e)(st(\d?))/g;


2 const str = 'test1test2';
3
4 const array = [...str.matchAll(regexp)];
5
6 console.log(array[0]);
7 // expected output: Array ["test1", "e", "st1", "1"]
8
9 console.log(array[1]);
10 // expected output: Array ["test2", "e", "st2", "2"]

 

-1

1 let str = "A drop of ink may make a million think";


2
3 console.log( str.search( /ink/i ) ); // 10

search

 
g

168
1 const reg1=/javascript/i;
2 const reg2=/javascript/ig;
3 console.log('hello Javascript Javascript Javascript'.replace(reg1,'js'));
4 //hello js Javascript Javascript
5 console.log('hello Javascript Javascript Javascript'.replace(reg2,'js'));
6 //hello js js js

 

1 console.log('12, 34, 56'.split(/,\s*/)) // ['12', '34', '56']

 

regexp.exec(str) str regexp

g regexp.exec(str) str.match(regexp)

g regexp.exec(str)
regexp.lastIndex regexp.lastIndex
regexp.lastIndex

1 let str = 'More about JavaScript at https://javascript.info';


2 let regexp = /javascript/ig;
3
4 let result;
5
6 while (result = regexp.exec(str)) {
7 console.log( `Found ${result[0]} at position ${result.index}` );
8 // Found JavaScript at position 11
9 // Found javascript at position 33
10 }

169
 

true/false

1 let str = "I love JavaScript";


2
3 //
4 console.log( /love/i.test(str) ); // true

 

1 const reg = /^[1-9][0-9]{4,14}$/


2 const isvalid = patrn.exec(s)

1 var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
2 const isvalid = patrn.exec(s)

url

170
1 const protocol = '(?<protocol>https?:)';
2 const host = '(?<host>(?<hostname>[^/#?:]+)(?::(?<port>\\d+))?)';
3 const path = '(?<pathname>(?:\\/[^/#?]+)*\\/?)';
4 const search = '(?<search>(?:\\?[^#]*)?)';
5 const hash = '(?<hash>(?:#.*)?)';
6 const reg = new RegExp(`^${protocol}\/\/${host}${path}${search}${hash}$`);
7 function execURL(url){
8 const result = reg.exec(url);
9 if(result){
10 result.groups.port = result.groups.port || '';
11 return result.groups;
12 }
13 return {
14 protocol:'',host:'',hostname:'',port:'',
15 pathname:'',search:'',hash:'',
16 };
17 }
18
19 console.log(execURL('https://localhost:8080/?a=b#xxxx'));
20 protocol: "https:"
21 host: "localhost:8080"
22 hostname: "localhost"
23 port: "8080"
24 pathname: "/"
25 search: "?a=b"
26 hash: "#xxxx"

search hash

171
1 function execUrlParams(str){
2 str = str.replace(/^[#?&]/,'');
3 const result = {};
4 if(!str){ //
5 return result;
6 }
7 const reg = /(?:^|&)([^&=]*)=?([^&]*?)(?=&|$)/y
8 let exec = reg.exec(str);
9 while(exec){
10 result[exec[1]] = exec[2];
11 exec = reg.exec(str);
12 }
13 return result;
14 }
15 console.log(execUrlParams('#'));// {}
16 console.log(execUrlParams('##'));//{'#':''}
17 console.log(execUrlParams('?q=3606&src=srp')); //{q: "3606", src: "srp"}
18 console.log(execUrlParams('test=a=b=c&&==&a='));//{test: "a=b=c", "":
"=", a: ""}





172
1 //
2 var array = [0, 1, 2, 3]
3 for(let i = 0; i < array.length; i++) {
4 array[i] = Math.pow(array[i], 2)
5 }
6
7 //
8 [0, 1, 2, 3].map(num => Math.pow(num, 2))





173
1 let double = value=>value*2;

1 test('double(2) 4', () => {


2 expect(double(2)).toBe(4);
3 })



174
1 const forEach = function(arr,fn){
2 for(let i=0;i<arr.length;i++){
3 fn(arr[i]);
4 }
5 }
6 let arr = [1,2,3];
7 forEach(arr,(item)=>{
8 console.log(item);
9 })

forEach

175
1 const once = (fn)=>{
2 let done = false;
3 return function(){
4 if(!done){
5 fn.apply(this,fn);
6 }else{
7 console.log(" ");
8 }
9 done = true;
10 }
11 }



1 let fn = (x,y)=>x+y;

1 const curry = function(fn){


2 return function(x){
3 return function(y){
4 return fn(x,y);
5 }
6 }
7 }
8 let myfn = curry(fn);
9 console.log( myfn(1)(2) );

curry

176
1 //
2 const curry = function(fn){
3 return function curriedFn(...args){
4 if(args.length<fn.length){
5 return function(){
6 return curriedFn(...args.concat([...arguments]));
7 }
8 }
9 return fn(...args);
10 }
11 }
12 const fn = (x,y,z,a)=>x+y+z+a;
13 const myfn = curry(fn);
14 console.log(myfn(1)(2)(3)(1));



1 function afn(a){
2 return a*2;
3 }
4 function bfn(b){
5 return b*3;
6 }
7 const compose = (a,b)=>c=>a(b(c));
8 let myfn = compose(afn,bfn);
9 console.log( myfn(2));

compose bfn -> af


n

177
1 const compose = (...fns)=>val=>fns.reverse().reduce((acc,fn)=>fn(acc),val);

compose

1 const pipe = (...fns)=>val=>fns.reduce((acc,fn)=>fn(acc),val);









178




XSS Web

XSS cookie

179
url

1 <input type="text" value="<%= getParameter("keyword") %>">


2 <button> </button>
3 <div>
4 <%= getParameter("keyword") %>
5 </div>

"><script>alert('XSS');</script>

1 <input type="text" value=""><script>alert('XSS');</script>">


2 <button> </button>
3 <div>
4 "><script>alert('XSS');</script>
5 </div>

<script>alert('XSS');</script>
cookie

XSS











180





















XSS

181
5 < 7 5 < 7

escapeHTML() 5 < 7

5 < 7

1 <div title="comment">5 &lt; 7</div>

5 < 7

.innerHTML .outerHTML document.write()


.textContent .setAttribute()

Vue/React v-html dangerouslySetInnerHTML


render innerHTML outerHTML

location onclick onerror onload onmouseove


r <a> href eval() setTimeout() setInterval
()

182
1 <!-- -->
2 < a href=" ">1</ a>
3
4 <script>
5 // setTimeout()/setInterval()
6 setTimeout("UNTRUSTED")
7 setInterval("UNTRUSTED")
8
9 // location
10 location.href = 'UNTRUSTED'
11
12 // eval()
13 eval("UNTRUSTED")



csrf get img

post

183
1 <form action="http://bank.example/withdraw" method=POST>
2 <input type="hidden" name="account" value="xiaoming" />
3 <input type="hidden" name="amount" value="10000" />
4 <input type="hidden" name="for" value="hacker" />
5 </form>
6 <script> document.forms[0].submit(); </script>

POST

1 < a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" taget=


"_blank">
2
3 <a/>





csrf

184
token

1 <input type=”hidden” name=”csrftoken” value=”tokenvalue”/>


Sql Sql

185
web





186
C

1 char * buffer;
2 buffer = (char*) malloc(42);
3
4 // Do something with buffer
5
6 free(buffer);

malloc free





JavaScript

187
1 var m = 0,n = 19 // m,n,add()
2 add(m, n) // a, b, c
3 console.log(n) // a,b,c
4 function add(a, b) {
5 a++
6 var c = a + b
7 return c
8 }



1 const arr = [1, 2, 3, 4];


2 console.log('hello world');

[1, 2, 3, 4] arr
1 arr

1 arr = null

arr null [1,2,3,4]

188




1 function foo(arg) {
2 bar = "this is a hidden global variable";
3 }

this

1 function foo() {
2 this.variable = "potential accidental global";
3 }
4 // foo this window
5 foo();

1 var someResource = getData();


2 setInterval(function() {
3 var node = document.getElementById('Node');
4 if(node) {
5 // node someResource
6 node.innerHTML = JSON.stringify(someResource));
7 }
8 }, 1000);

id DOM someRes
ource someResource

189
1 function bindEvent() {
2 var obj = document.createElement('XXX');
3 var unused = function () {
4 console.log(obj, ' obj obj ');
5 };
6 obj = null; //
7 }

DOM

1 const refA = document.getElementById('refA');


2 document.body.removeChild(refA); // dom
3 console.log(refA, 'refA'); // console div
4 refA = null;
5 console.log(refA, 'refA'); //

addEventListener removeEventListen
er





190
JavaScript

1 class Car{
2 constructor(color,speed){
3 this.color = color
4 this.speed = speed
5 // ...
6 }
7 }

1 //
2 class Truck extends Car{
3 constructor(color,speed){
4 super(color,speed)
5 this.Container = true //
6 }
7 }

191
1 class Truck extends Car{
2 constructor(color,speed){
3 super(color,speed)
4 this.color = "black" //
5 this.Container = true //
6 }
7 }


JavaScripy



192
1 function Parent() {
2 this.name = 'parent1';
3 this.play = [1, 2, 3]
4 }
5 function Child() {
6 this.type = 'child2';
7 }
8 Child1.prototype = new Parent();
9 console.log(new Child())

1 var s1 = new Child2();


2 var s2 = new Child2();
3 s1.play.push(4);
4 console.log(s1.play, s2.play); // [1,2,3,4]

s1 play s2



call Parent

193
1 function Parent(){
2 this.name = 'parent1';
3 }
4
5 Parent.prototype.getName = function () {
6 return this.name;
7 }
8
9 function Child(){
10 Parent1.call(this);
11 this.type = 'child'
12 }
13
14 let child = new Child();
15 console.log(child); //
16 console.log(child.getName()); //



194
1 function Parent3 () {
2 this.name = 'parent3';
3 this.play = [1, 2, 3];
4 }
5
6 Parent3.prototype.getName = function () {
7 return this.name;
8 }
9 function Child3() {
10 // Parent3()
11 Parent3.call(this);
12 this.type = 'child3';
13 }
14
15 // Parent3()
16 Child3.prototype = new Parent3();
17 //
18 Child3.prototype.constructor = Child3;
19 var s3 = new Child3();
20 var s4 = new Child3();
21 s3.play.push(4);
22 console.log(s3.play, s4.play); //
23 console.log(s3.getName()); // 'parent3'
24 console.log(s4.getName()); // 'parent3'

Par
ent3



Object.create

195
1 let parent4 = {
2 name: "parent4",
3 friends: ["p1", "p2", "p3"],
4 getName: function() {
5 return this.name;
6 }
7 };
8
9 let person4 = Object.create(parent4);
10 person4.name = "tom";
11 person4.friends.push("jerry");
12
13 let person5 = Object.create(parent4);
14 person5.friends.push("lucy");
15
16 console.log(person4.name); // tom
17 console.log(person4.name === person4.getName()); // true
18 console.log(person5.name); // parent4
19 console.log(person4.friends); // ["p1", "p2", "p3","jerry","lucy"]
20 console.log(person5.friends); // ["p1", "p2", "p3","jerry","lucy"]

Object.create



196
1 let parent5 = {
2 name: "parent5",
3 friends: ["p1", "p2", "p3"],
4 getName: function() {
5 return this.name;
6 }
7 };
8
9 function clone(original) {
10 let clone = Object.create(original);
11 clone.getFriends = function() {
12 return this.friends;
13 };
14 return clone;
15 }
16
17 let person5 = clone(parent5);
18
19 console.log(person5.getName()); // parent5
20 console.log(person5.getFriends()); // ["p1", "p2", "p3"]



Object.create

197
1 function clone (parent, child) {
2 // Object.create
3 child.prototype = Object.create(parent.prototype);
4 child.prototype.constructor = child;
5 }
6
7 function Parent6() {
8 this.name = 'parent6';
9 this.play = [1, 2, 3];
10 }
11 Parent6.prototype.getName = function () {
12 return this.name;
13 }
14 function Child6() {
15 Parent6.call(this);
16 this.friends = 'child5';
17 }
18
19 clone(Parent6, Child6);
20
21 Child6.prototype.getFriends = function () {
22 return this.friends;
23 }
24
25 let person6 = new Child6();
26 console.log(person6); //{friends:"child5",name:"child5",play:[1,2,3],__pro
to__:Parent6}
27 console.log(person6.getName()); // parent6
28 console.log(person6.getFriends()); // child5

ES6 extends JavaScript

198
1 class Person {
2 constructor(name) {
3 this.name = name
4 }
5 //
6 // Person.prototype.getName = function() { }
7 // getName() {...}
8 getName = function () {
9 console.log('Person:', this.name)
10 }
11 }
12 class Gamer extends Person {
13 constructor(name, age) {
14 // “this” super()
15 super(name)
16 this.age = age
17 }
18 }
19 const asuna = new Gamer('Asuna', 20)
20 asuna.getName() //

babel extends



199
Object.create
extends





1 0.1 + 0.2 === 0.3 // false

false



200
JavaScript Number Number IEEE754

javaScript

201
10000000011 10111



1 0.1 + 0.2 === 0.3 // false

javascript

1 // 0.1 0.2
2 0.00011001100110011001100110011001100110011001100110011010 +
3 0.0011001100110011001100110011001100110011001100110011010 =
4 0.0100110011001100110011001100110011001100110011001100111
5
6 // 0.30000000000000004

false

x=0.1 0.1

2^53=9007199254740992 9.007199254740992

toPrecision(16)

1 .10000000000000000555.toPrecision(16)
2 // 0.1000000000000000 0.1

0.1 0.1

202
1 0.1.toPrecision(21) = 0.100000000000000005551

9007199254740992

2^1024 - 1
2^1024 Infinity

1 > Math.pow(2, 1023)


2 8.98846567431158e+307
3
4 > Math.pow(2, 1024)
5 Infinity

(2^53, 2^63)

(2^53, 2^54)

(2^54, 2^55)

bignumber.js





1.4000000000000001 toPrecision parse


Float

203
1 parseFloat(1.4000000000000001.toPrecision(12)) === 1.4 // True

1 function strip(num, precision = 12) {


2 return +parseFloat(num.toPrecision(precision));
3 }

+-*/ toPrecision

1 /**
2 *
3 */
4 function add(num1, num2) {
5 const num1Digits = (num1.toString().split('.')[1] || '').length;
6 const num2Digits = (num2.toString().split('.')[1] || '').length;
7 const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
8 return (num1 * baseNum + num2 * baseNum) / baseNum;
9 }

Math.js BigDecimal.js



204


pow(x, n) x n

1 function pow(x, n) {
2 let result = 1;
3
4 // x result n
5 for (let i = 0; i < n; i++) {
6 result *= x;
7 }
8 return result;
9 }

1 function pow(x, n) {
2 if (n == 1) {
3 return x;
4 } else {
5 return x * pow(x, n - 1);
6 }
7 }

pow(x, n)

205
1 if n==1 = x
2 /
3 pow(x, n) =
4 \
5 else = x * pow(x, n - 1)

pow n == 1

pow(2, 4)

 pow(2, 4) = 2 * pow(2, 3)

 pow(2, 3) = 2 * pow(2, 2)

 pow(2, 2) = 2 * pow(2, 1)

 pow(2, 1) = 2



206
1 function factorial(n) {
2 if (n === 1) return 1;
3 return n * factorial(n - 1);
4 }
5
6 factorial(5) // 120

n
O(n)

1 function factorial(n, total) {


2 if (n === 1) return total;
3 return factorial(n - 1, n * total);
4 }
5
6 factorial(5, 1) // 120



207
1 function sumArray(arr, total) {
2 if(arr.length === 1) {
3 return total
4 }
5 return sum(arr, total + arr.pop())
6 }

1 function factorial2 (n, start = 1, total = 1) {


2 if(n <= 2){
3 return total
4 }
5 return factorial2 (n -1, total, total + start)
6 }

1 let a = [1,2,3, [1,2,3, [1,2,3]]]


2 //
3 let a = [1,2,3,1,2,3,1,2,3]
4 //
5 function flat(arr = [], result = []) {
6 arr.forEach(v => {
7 if(Array.isArray(v)) {
8 result = result.concat(flat(v, []))
9 }else {
10 result.push(v)
11 }
12 })
13 return result
14 }

208
1 let obj = {
2 a: '1',
3 b: {
4 c: '2',
5 D: {
6 E: '3'
7 }
8 }
9 }
10 //
11 let obj = {
12 a: '1',
13 b: {
14 c: '2',
15 d: {
16 e: '3'
17 }
18 }
19 }
20
21 //
22 function keysLower(obj) {
23 let reg = new RegExp("([A-Z]+)", "g");
24 for (let key in obj) {
25 if (obj.hasOwnProperty(key)) {
26 let temp = obj[key];
27 if (reg.test(key.toString())) {
28 // temp obj
29 temp = obj[key.replace(reg, function (result) {
30 return result.toLowerCase()
31 })] = obj[key];
32 //
33 delete obj[key];
34 }
35 //
36 if (typeof temp === 'object' || Object.prototype.toString.call
(temp) === '[object Array]') {
37 keysLower(temp);
38 }
39 }
40 }
41 return obj;
42 };

209


210

You might also like