-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
1634 lines (1478 loc) · 39.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// deep clone
const deepClone = function(obj) {
if (!obj) return obj
let newObj = Array.isArray ? [] : {}
for (let key in obj) {
let val = obj[key]
if (typeof val === 'object') {
newObj[key] = deepClone(val)
} else {
newObj[key] = val
}
}
return newObj
}
const target = {
name: 'ABC',
key: null,
age: 28,
bool: false,
address: {
street: 'Station Road',
city: 'Pune',
number: 123,
},
keys: [1,2,3,4]
}
console.log(deepClone(target))
// deep clone for circle and date and function
const deepClone = function(obj, map = new Map()) {
if (!obj) return obj
if (map.has(obj)) { // 判断是否循环引用
return map.get(obj)
}
let newObj
if (Object.prototype.toString.call(obj) == "[object Object]") {
newObj = {}
map.set(obj, newObj);
for (let key in obj) {
let val = obj[key]
newObj[key] = deepClone(val, map)
}
} else if (Object.prototype.toString.call(obj) == "[object Array]") {
newObj = []
map.set(obj, newObj);
for (let key in obj) {
let val = obj[key]
newObj[key] = deepClone(val, map)
}
} else if (Object.prototype.toString.call(obj) == "[object Function]") {
newObj = obj.clone()
} else if (obj.constructor === Object.prototype.toString.call(obj) == "[object Date]") {
newObj = new Date(obj)
} else {
newObj = obj
}
return newObj
}
Function.prototype.clone = function() {
var newfun = new Function('return ' + this.toString())();
for (var key in this)
newfun[key] = this[key];
return newfun;
};
const isDate = function(date) {
return date instanceof Date
// if (Object.prototype.toString.call(date) === "[object Date]") {
// return true
// }
// return false
}
console.log(deepClone(1)) // 1
console.log(deepClone(null)) // null
console.log(deepClone(undefined)) // undefined
console.log(deepClone([1, 2, 3]))
console.log(deepClone({ a: new Date(), b: null, c: 123, d: [1,2,3] }))
const a = {
b: {
c: null,
},
};
a.b.c = a;
console.log(deepClone(a))
// debounce
const debounce = function(fn, timeout = 300) {
let timer = null
return function(...args) {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, timeout)
}
}
function saveInput(id){
console.log('Saving data', id);
}
const testDebounce = debounce((id) => saveInput(id));
setInterval(() => {
testDebounce(12)
}, 250)
// throttle
const throttle = function(fn, timeout = 500) {
let waiting = false
return function(...args) {
if (waiting) return
waiting = true
fn.apply(this, args)
setTimeout(() => {
waiting = false
}, timeout)
}
}
function saveInput(id){
console.log('Saving data', id);
}
const testThrottle = throttle((id) => saveInput(id));
setInterval(() => {
testThrottle(15)
}, 250)
// promise all
const promiseAll = function(inputs) {
return new Promise((resolve, reject) => {
let length = inputs.length
let count = 0
let data = []
for (let fn of inputs) {
fn.apply(this)
.then((res) => {
count++
data.push(res)
if (count === length) resolve(data)
}).catch((err) => {
reject(err)
})
}
})
}
const request = function(id) {
return new Promise((resolve, reject) => {
let timeout = Math.floor(Math.random() * 1000) + 500
setTimeout(() => {
resolve(`${id}: ${timeout}ms`);
}, timeout);
})
}
let inputs = []
for (let i = 0; i < 22; i++) {
inputs.push(() => request(i))
}
promiseAll(inputs)
.then((res) => {
console.log('promiseAll', res)
})
// promise race
const promiseRace = function(inputs) {
return new Promise((resolve, reject) => {
for (let fn of inputs) {
fn.apply(this)
.then((res) => {
resolve(res)
}).catch((err) => {
reject(err)
})
}
})
}
promiseRace(inputs)
.then((res) => {
console.log('promiseRace', res)
})
// promise schedule
const Scheduler = function(max = 3) {
let currentJobs = 0
let queue = []
function start() {
if (queue.length === 0 || currentJobs >= max) return
currentJobs++
let [fn, resolve, reject] = queue.shift()
fn.apply(this).then((res) => {
currentJobs--
start()
resolve(res)
}).catch((err) => {
currentJobs--
start()
reject(err)
})
}
return function(fn) {
return new Promise((resolve, reject) => {
queue.push([fn, resolve, reject])
start()
})
}
}
const scheduler = Scheduler(6)
const request = function(id) {
return new Promise((resolve, reject) => {
let timeout = Math.floor(Math.random() * 1000) + 500
setTimeout(() => {
resolve(`${id}: ${timeout}ms`);
}, timeout);
})
}
for (let i = 0; i < 25; i++) {
scheduler(() => request(i))
.then((res) => {
console.log('scheduler', res)
})
}
// my reduce
Array.prototype.myReduce = function(fn, initialValue) {
let nums = this
let res = 0
if (initialValue) res = initialValue
for (let i = 0; i < nums.length; i++) {
res = fn(res, nums[i])
}
return res
}
let arr = [1,2,3,4,3,1]
let myReduceRes = arr.myReduce((a, b) => {
return a + b
})
let reduceRes = arr.reduce((a, b) => {
return a + b
})
console.log('myReduce', myReduceRes)
console.log('reduce', reduceRes)
// my AJAX
function ajax(method, url, body = {}) {
return new Promise((resolve, reject) => {
// 0. create XMLHttpRequest instance
let xhr = new XMLHttpRequest()
// 1. define request
xhr.open(method, url, true)
// xhr.setRequestHeader("Content-Type", "application/json");
// 2. define response
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
let res = xhr.response
resolve(res)
} else {
reject()
}
}
// 3. define error
xhr.onerror = () => {
reject()
}
// 4. send request
xhr.send() // get
// xhr.send(body) // post
})
}
ajax('GET', 'https://ipv4.icanhazip.com/')
.then((res) => {
console.log(res)
})
// my instanceof
const myInstanceof = function(original, target) {
let proto = original.__proto__
while (proto) {
if (proto === target.prototype) {
return true
}
proto = proto.__proto__
}
return false
}
const myInstanceofTest = [1,2,3]
console.log(myInstanceof(myInstanceofTest, Array)); // true
console.log(myInstanceof(myInstanceofTest, Object)); // true
console.log(myInstanceof(myInstanceofTest, Function)); // false
// my typeof
const myTypeof = function(target) {
let type = Object.prototype.toString.apply(target)
type = type.split(' ')[1]
return type.slice(0, -1).toLowerCase()
}
console.log(myTypeof({}))
console.log(myTypeof([]))
console.log(myTypeof(Function))
console.log(myTypeof(123))
console.log(myTypeof(null))
console.log(myTypeof(''))
console.log(myTypeof(new Date()))
// my new
const myNew = function(fn, ...args) {
let context = Object.create(fn.prototype)
let res = fn.apply(context, args)
// if res is undefined and nothing to return, return context
if (res instanceof Object) {
return res
} else {
return context
}
}
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = myNew(Person, 'fl', 32)
console.log(person)
// my call
Function.prototype.myCall = function(context, ...args) {
let obj = context || window
obj.fn = this
let res = obj.fn(...args)
delete obj.fn
return res
}
// my apply
Function.prototype.myApply = function(context, arr) {
// 定义 this,上下文
let obj = context || window
// 函数放进上下文的fn中
obj.fn = this
// 执行 fn,这样做fn就可以看到context了,闭包
let res = obj.fn(...arr)
// 要删除 fn
delete obj.fn
return res
}
const obj = {
name: 'alex'
}
const myApplyTestFn = function(a, b) {
console.log(a,b)
console.log(this.name)
}
console.log('myCall', myApplyTestFn.myCall(obj, 1,2))
console.log('myApply', myApplyTestFn.myApply(obj, [1,2]))
// my bind
Function.prototype.myBind = function(context) {
const fn = this
const args = [...arguments].slice(1)
return function(...innerArgs) {
let moreArgs = [...args, ...innerArgs]
return fn.apply(context, moreArgs)
}
}
const context = {
name: 'alex'
}
const myBindTestFn = function(name, age, school){
console.log(name) // 'Ann'
console.log(age) // 32
console.log(school) // '126'
}
let myBindFn = myBindTestFn.myBind(context, 'Ann')
myBindFn(32, '126')
// json to string
const jsonToString = function(obj) {
if (!obj) return obj
let str = ``
if (Object.prototype.toString.call(obj) === '[object Array]') {
str = `[`
let keys = Object.keys(obj)
for (let j = 0; j < keys.length; j++) {
let key = keys[j]
let val = obj[key]
let res = jsonToString(val)
str = `${str}${res}`
if (j !== keys.length - 1) str = `${str},` // remove the last ,
}
str = `${str}]`
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
str = `{`
let keys = Object.keys(obj)
for (let j = 0; j < keys.length; j++) {
let key = keys[j]
let val = obj[key]
let res = jsonToString(val)
str = `${str}"${key}":${res}`
if (j !== keys.length - 1) str = `${str},` // remove the last ,
}
str = `${str}}`
} else {
// other than array or object
return `${obj}`
}
return str
}
let jsonToStringTest = {
a: 11,
b: {
b: 22,
c: {
D: 33,
e: [44,55,66]
}
}
};
console.log(JSON.stringify(jsonToStringTest))
console.log(jsonToString(jsonToStringTest))
// my trim
String.prototype.myTrim = function() {
let str = this
const trimLeft = function(string) {
for (let i = 0; i < string.length; i++) {
if (string.charAt(i) !== ' ') {
return string.substring(i, string.length)
}
}
return string
}
const trimRight = function(string) {
for (let i = string.length - 1; i >= 0; i--) {
if (string.charAt(i) !== ' ') {
return string.substring(0, i + 1)
}
}
return string
}
return trimRight(trimLeft(str))
}
console.log(' 123123123 '.myTrim())
// DOM2JSON
/*
<div>
<span>
<a></a>
</span>
<span>
<a></a>
<a></a>
</span>
</div>
把上诉dom结构转成下面的JSON格式
{
tag: 'DIV',
children: [
{
tag: 'SPAN',
children: [
{ tag: 'A', children: [] }
]
},
{
tag: 'SPAN',
children: [
{ tag: 'A', children: [] },
{ tag: 'A', children: [] }
]
}
]
}
*/
const dom2json = function(domTree) {
// create an obj
let obj = {}
// get the tag name
obj.tag = domTree.tagName
// setup array for children
obj.children = []
// iterate each child node
domTree.childNodes.forEach((child) => {
// dfs, it will return json of this child
obj.children.push(dom2json(child))
})
return obj
}
// my curry
const myCurry = function(fn) {
// fn.length gives the length of arguments of fn
let length = fn.length
// get arguments from myCurry
let args = [...arguments].slice(1)
return function(...innerArgs) {
// concat myCurry and currying arguments
let moreArgs = [...args, ...innerArgs]
// if current length === fn.length, we can return the result
if (length === moreArgs.length) return fn.apply(this, moreArgs)
// if not yet finished, recursion and call myCurry.apply with the correct arguments
else return myCurry.apply(this, [fn, ...moreArgs])
}
}
function sum(a, b, c) {
return a + b + c;
}
let currying = myCurry(sum)
console.log(currying(1)(2)(3))
console.log(currying(1,2,3))
// tree to list
const treeToList = function(tree) {
let list = []
treeToListHelper(tree, list)
list.sort((a,b) =>a.id-b.id)
return list
}
const treeToListHelper = function(tree, list) {
if (!tree) return
for (let item of tree) {
let id = item.id
let name = item.name
let parentId = item.parentId
list.push({ id, name, parentId })
treeToListHelper(item.children, list)
}
}
let tree = [
{
id: 1,
name: '部门A',
parentId: 0,
children: [
{
id: 3,
name: '部门C',
parentId: 1,
children: [
{
id: 6,
name: '部门F',
parentId: 3
}
]
},
{
id: 4,
name: '部门D',
parentId: 1,
children: [
{
id: 8,
name: '部门H',
parentId: 4
}
]
}
]
},
{
id: 2,
name: '部门B',
parentId: 0,
children: [
{
id: 5,
name: '部门E',
parentId: 2
},
{
id: 7,
name: '部门G',
parentId: 2
}
]
}
];
console.log(treeToList(tree))
// list to tree
const listToTree = function(list) {
let map = new Map()
for (let item of list) {
let name = item.name
let id = item.id
let parentId = item.parentId
let children = map.get(parentId) || []
children.push({id, name, parentId})
map.set(parentId, children)
}
return appendChildren(0, map)
}
const appendChildren = function(parentId, map) {
let children = map.get(parentId)
if (!children) return null
for (let child of children) {
let res = appendChildren(child.id, map)
if (res) child.children = res
}
return children
}
let list = [
{id:1, name:'部门A', parentId:0},
{id:2, name:'部门B', parentId:0},
{id:3, name:'部门C', parentId:1},
{id:4, name:'部门D', parentId:1},
{id:5, name:'部门E', parentId:2},
{id:6, name:'部门F', parentId:3},
{id:7, name:'部门G', parentId:2},
{id:8, name:'部门H', parentId:4}
];
console.log(listToTree(list))
// flatten array
const flattenArray = function(array) {
return flattenArrayHelper(array)
}
const flattenArrayHelper = function(array) {
let res = []
for (let i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
res = res.concat(flattenArrayHelper(array[i]))
} else {
res.push(array[i])
}
}
return res
}
console.log(flattenArray([12,[1,2,3],3,[2,4,[4,[3,4],2]]]));
// dedup array
const dedupArray = function(array) {
new Set(array)
return [...new Set(array)]
}
console.log(dedupArray([12, 1, 2, 3, 3, 2, 4, 4, 3, 4, 2]))
// 大数相加
function add(a ,b){
let indexa = a.length - 1
let indexb = b.length - 1
let carry = 0
let res = ``
while (indexa >= 0 || indexb >= 0) {
let numa = indexa >= 0 ? a.charAt(indexa) : 0
let numb = indexb >= 0 ? b.charAt(indexb) : 0
let sum = parseInt(numa) + parseInt(numb) + carry
carry = sum >= 10 ? 1 : 0
sum = sum >= 10 ? sum - 10 : sum
res = `${sum}${res}`
indexa--
indexb--
}
if (carry !== 0) {
res = `1${res}`
}
return res
}
let a = "9007199254740991";
let b = "1234567899999999999";
console.log(add(a, b))
// path to obj
const pathToObjData = {
'a.b': 1,
'a.c': 2,
'a.d.e': 5,
'b[0]': 1,
'b[1]': 3,
'b[2].a': 2,
'b[2].b': 3,
'c': 3
}
const pathToObj = function(pathList) {
let res = {}
for (let path in pathList) {
let pathArr = path.split('.')
pathToObjHelper(pathArr, pathList[path], res)
}
return res
}
const pathToObjHelper = function(pathArr, val, res) {
if (pathArr.length === 0) {
return val
}
let key = pathArr.shift()
let obj = res[key] ? res[key] : {}
res[key] = pathToObjHelper(pathArr, val, obj)
return res
}
console.log(pathToObj(pathToObjData))
// obj to path
const objToPathData = {
a: {
b: 1,
c: 2,
d: {e: 5}
},
b: [1, 3, {a: 2, b: 3}],
c: 3
}
const objToPath = function(obj) {
let res = {}
objToPathHelper(obj, '', res)
return res
}
const objToPathHelper = function(obj, path, res) {
if (!obj) return
if (Array.isArray(obj)) {
for (let key in obj) {
const pathKey = path ? `${path}[${key}]` : `${path}${key}`
objToPathHelper(obj[key], pathKey, res)
}
} else if (typeof obj === 'object') {
for (let key in obj) {
const pathKey = path ? `${path}.${key}` : `${path}${key}`
objToPathHelper(obj[key], pathKey, res)
}
} else {
res[path] = obj
}
}
console.log(objToPath(objToPathData))
// string to json
const jsonString = '{ "age": 20, "name": "jack" }'
const stringToJson = function(jsonString) {
return (new Function('return ' + jsonString))();
}
console.log(stringToJson(jsonString))
// 分红包
const redenvelope = function(people, amount) {
let randSum = 0
let randList = []
let res = []
for (let i = 0; i < people; i++) {
let rand = Math.random()
randList.push(rand)
randSum += rand
}
randList.forEach((rand) => {
res.push(amount * rand / randSum)
})
return res
}
const redenvelopeRes = redenvelope(13, 200)
console.log('redenvelopeRes', { redenvelopeRes, sum: redenvelopeRes.reduce((acc,val) => {
return acc + val
})
})
// vdom to rdom
// const vdom = {
// tag: 'DIV',
// attrs:{
// id:'app'
// },
// children: [
// {
// tag: 'SPAN',
// children: [
// { tag: 'A', children: [] }
// ]
// },
// {
// tag: 'SPAN',
// children: [
// { tag: 'A', children: [] },
// { tag: 'A', children: [] }
// ]
// }
// ]
// }
/*
把上诉虚拟Dom转化成下方真实Dom
<div id="app">
<span>
<a></a>
</span>
<span>
<a></a>
<a></a>
</span>
</div>
*/
const vdomToRdom = function(vdom) {
let tag = vdom.tag.toLowerCase()
let dom = document.createElement(tag)
if (vdom.attrs) {
for (let key in vdom.attrs) {
let val = vdom.attrs[key]
dom.setAttribute(key, val)
}
}
for (let child of vdom.children) {
let childNode = vdomToRdom(child)
dom.appendChild(childNode)
}
return dom
}
console.log(vdomToRdom(vdom))
// LazyMan
/*
实现一个LazyMan,可以按照以下方式调用:
LazyMan(“Hank”)输出:
Hi! This is Hank!
LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~
LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
Hi This is Hank!
Eat dinner~
Eat supper~
LazyMan(“Hank”).eat(“supper”).sleepFirst(5)输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
*/
class LazyMan {
constructor(name) {
this.tasks = []
// 按照顺序推入task队列
this.tasks.push(() => {
setTimeout(() => {
console.log(`Hi This is ${name}!`)
this.next()
}, 0)
})
// 关键不然不会执行,首次执行,但是希望在同步任务之后执行
setTimeout(() => {
this.next()
}, 0)
}
// 每次执行完一个任务,执行next,来执行下一个任务
next() {
let task = this.tasks.shift()
task && task()
}
sleep(sec) {
// 按照顺序推入task队列
this.tasks.push(() => {
setTimeout(() => {
console.log(`Wake up after ${sec}`)
this.next()
}, sec*1000)
})
// 返回this,继续执行lazy man的方法
return this
}
eat(meal) {
// 按照顺序推入task队列
this.tasks.push(() => {
setTimeout(() => {
console.log(`Eat ${meal}~`)
this.next()
}, 0)
})
return this
}
sleepFirst(sec) {
// 推入task首部执行
this.tasks.unshift(() => {
setTimeout(() => {
console.log(`Wake up after ${sec}`)
this.next()
}, sec*1000)
})
return this
}
}
new LazyMan("Hank")
new LazyMan("Hank").sleep(10).eat("dinner")
new LazyMan("Hank").eat("dinner").eat("supper")
new LazyMan("Hank").eat("supper").sleepFirst(5)
// 每个一秒打印一个数字,用setTimeout来实现
const printNumber = function(n) {
// print n, n times
for (var i = 0; i < n; i++) {
setTimeout(() => {
console.log(i)
}, i * 1000)
}
// print 0 to n - 1, n times
for (let i = 0; i < n; i++) {
setTimeout(() => {
console.log(i)
}, i * 1000)
}
}
printNumber(6)
// this的指向问题,看题目说答案
var length = 10;
function fn() {
return this.length + 1;
}
var obj1 = {
length: 5,
test1: function() {
return fn()
}
}
obj1.test2 = fn;
console.log(obj1.test1.call()) // 11
console.log(obj1.test1()) // 11
console.log(obj1.test2.call()) // 11
console.log(obj1.test2()) // 6
var name = "window";
var person = {
name: "person",
sayName: function () {
console.log(this.name);
}
};
function sayName() {
var sss = person.sayName;
sss(); // window
person.sayName(); // person
(person.sayName)(); // person
(b = person.sayName)(); // window
}
sayName();
var name = 'window'
var person1 = {
name: 'person1',
foo1: function () {
console.log(this.name)
},
foo2: () => console.log(this.name),
foo3: function () {
return function () {
console.log(this.name)
}
},
foo4: function () {
return () => {
console.log(this.name)
}
}
}
var person2 = { name: 'person2' }
// 隐式绑定,肯定是person1
person1.foo1(); // person1
// 隐式绑定和显示绑定的结合,显示绑定生效,所以是person2
person1.foo1.call(person2); // person2