前端 笔试 选牛客网 美团
this指针和任务队列
var name = 'global';
var obj = {
name: 'local',
foo: function(){
this.name = 'foo';
}.bind(window)
};
var bar = new obj.foo();
setTimeout(function() {
console.log(window.name);
}, 0);
console.log(bar.name);
var bar3 = bar2 = bar;
bar2.name = 'foo2';
console.log(bar3.name)
'foo'
'foo2'
'global'
由于new绑定的优先级大于bind绑定, 所以内部this还是实例本身
定时器任务在异步队列中, 只有在同步队列执行完毕后才从异步队列中按时间顺序执行任务, 同时计时器都有一个默认最小的执行时间 谷歌:5~6ms IE10~13ms
宏任务微任务
setTimeout(() => console.log('a'));
Promise.resolve().then(
() => console.log('b’);
).then(
() => Promise.resolve('c').then(
(data) => {
setTimeout(() => console.log('d'));
console.log('f');
return data;
}
)
).then(data => console.log(data));
b
f
c
a
d
定时器任务属于宏任务, 并且需要先在任务队列等待, 执行栈清空, 才会在任务队列中按顺序选任务进去
promise属于异步微任务, 在本轮同步任务结束之前执行
箭头函数的resolve传递的参数作为下一个then的参数
解析:
// 定时器任务属于宏任务,并且需要先在任务队列等待,等到同步任务执行完,执行栈清空,才会在任务队列中按顺序选任务进去
setTimeout(() => console.log('a'));//4. 打印a
//Promise 属于异步微任务,在本轮同步任务结束之前执行
Promise.resolve().then(
// 1. 打印 b
() => console.log('b') // 单引号要改为',然后去掉;号
).then(
// 箭头函数的resolve传递的参数作为下一个then的参数
() => Promise.resolve('c').then(
// 执行箭头函数
(data) => {
// 把定时器任务也放入任务队列中等待,在第一个定时器之后
setTimeout(() => console.log('d')); //5. 打印d
// 2.打印 f
console.log('f');
// 此时返回的 数据作为下一个then的参数
return data;
}
)
).then(data => console.log(data)); // 3.打印 c
请写出下面ES6代码编译后所生产的ES5代码
class Person {
constructor (name) {
this.name = name;
}
greet () {
console.log(`Hi, my name is ${this.name}`);
}
greetDelay (time) {
setTimeout(() => {
console.log(`Hi, my name is ${this.name}`);
}, time);
}
}
var Person = (function () {
function Person(name) {
this._name = name;
}
Person.prototype.greet = function () {
console.log("Hi, my name is" + this._name);
};
Person.prototype.greetDelay = function (time) {
var _this = this;
setTimeout(function () {
console.log("Hi, my name is " + _this._name);
}, time);
};
return Person;
})();
使用局部变量保存this, 避免定时器中的this指向window