Codog

关注微信公众号:Codog代码狗

0%

原生具备 Iterator 接口的数据结构如下。

Array
Map
Set
String
TypedArray
函数的 arguments 对象

1
2
3
4
5
6
function test(){
for(let arg of arguments){
console.log(arg)
}
}
test(1,2,3) // 1 2 3

NodeList 对象

Promise.all

先看all的行为:

image

自己实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 非实例上的方法,所以直接在Promise上实现
Promise.myAll = function(list) {
return new Promise((resolve, reject) => {
const length = list.length;
let count = 0;
const res = [];
for (let i = 0; i < length; i++) {
Promise.resolve(list[i]).then(r => {
res[i] = r;
count++;
if (count === length) {
resolve(res)
}
}).catch(e => {
reject(e)
})
}
})
}

测试一下:

1
2
3
4
5
6
7
Promise.myAll([1, 2, Promise.reject('error')]).then(res => console.log(res)).catch(e => console.error('Get error: ', e))

Promise.myAll([1, 2, Promise.resolve('success')]).then(res => console.log(res)).catch(e => console.error('Get error: ', e))

// Output: 这里的顺序也是个问题。。为啥成功的在前面呢,success在前面也是成功的先返回
[1, 2, "success"]
Get error: error

Promise.race

p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。

Promise A+规范

https://github.com/xieranmaya/Promise3/blob/master/Promise3.js
https://github.com/xieranmaya/blog/issues/3

最后

记住了之前理解有误的地方,一个promise是可以被多次使用,也可以分开执行:

1
2
3
4
5
6
7
8
9
10
11
// 比如某个promise需要一定的执行时间,可以放在开头让它提前执行,在后面需要的时候再引用,可以节省一定时间

let promise = new Promise(resolve => {
resolve(data)
})

// other code

promise.then(res => func1(res))

promise.then(res => func2(res))

then与catch对后续状态的改变

image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Foo(){
getName=function(){console.log(1);};
return this;
}
Foo.getName=function(){ console.log(2);};
Foo.prototype.getName=function(){console.log(3);};
var getName=function(){console.log(4);};
function getName(){console.log(5);}

Foo.getName();
getName();
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();
new new Foo().getName();

尝试说出输出结果?

阅读全文 »

严格模式的意义是什么?

  • 消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为;
  • 消除代码运行的一些不安全之处,保证代码运行的安全;
  • 提高编译器效率,增加运行速度;
  • 为未来新版本的Javascript做好铺垫。

如何进入严格模式?

标识为一段无赋值的字符串:”use strict”;

除了在js文件首行,也可以在方法内部:

1
2
3
4
5
6
7
function strict(){
"use strict";
return "这是严格模式。";
}
function notStrict() {
return "这是正常模式。";
}

严格模式与非严格模式的区别?

  • 全局变量显式声明
  • 静态绑定
    • 禁止使用with语句
    • 创设eval作用域
  • 4.3 增强的安全措施
    • 禁止this关键字指向全局对象
    • 禁止在函数内部遍历调用栈(函数内部调用caller或arguments参数)
  • 。。。。

详细内容参考阮老师的文章: https://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html