第1题:
function fun(x,y){
console.log(y);
return {
fun:function(m){
return fun(m,x);
}
}
}
var a = fun(0); a.fun(1);a.fun(2);a.fun(3);
var b = fun(0).fun(1).fun(2).fun(3)
第2题(来源:https://blog.youkuaiyun.com/FE_dev/article/details/83278508)
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(console.log)
解析:Promise.resolve
方法的参数如果是一个原始值,或者是一个不具有 then
方法的对象,则 Promise.resolve
方法返回一个新的 Promise
对象,状态为resolved
,Promise.resolve
方法的参数,会同时传给回调函数。
then
方法接受的参数是函数,而如果传递的并非是一个函数,它实际上会将其解释为 then(null)
,这就会导致前一个 Promise
的结果会穿透下面。
第3题(https://mp.weixin.qq.com/s/VglgdC4YGk_fXOUgjBMQIA)
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius
};
shape.diameter();//20
shape.perimeter();//NaN
解析:对于箭头函数,this
关键字指向是它所在上下文(定义时的位置)的环境(why),与普通函数不同(why)! 这意味着当我们调用perimeter
时,它不是指向shape
对象,而是指其定义时的环境(window)。没有值radius
属性,返回undefined
。
看完两个 why 后,可以有个初步判断:1 不通过箭头声明的函数,this指向调用的它的上下文,可能是window,也可能是某个对象(通过 obj.函数名 调用的方式)2 通过箭头声名的函数,this指向定义时的父级上下文(为什么是父级上下文,好好看看两个 why)。或许还有疑问,那就接着看这个。
第4题(来源:https://mp.weixin.qq.com/s/VglgdC4YGk_fXOUgjBMQIA)
const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
可以在控制台输出看看!如果b是声明过,a.b a[b] 和 a['b'] 是不一样的。
第5题(来源:https://mp.weixin.qq.com/s/VglgdC4YGk_fXOUgjBMQIA)
<div onclick="console.log('div')">
<p onclick="console.log('p')">
点我后是先打印出p还是div
<p/>
</div>
默认情况下,事件是在冒泡阶段触发执行,所以你懂的!
第6题(来源:https://mp.weixin.qq.com/s/VglgdC4YGk_fXOUgjBMQIA)
代码输出什么?
(() => {
let x, y;
try {
throw new Error();
} catch (x) {
(x = 1), (y = 2);
console.log(x);
}
console.log(x);
console.log(y);
})();
如果想看结果,请复制到控制台!如果想不明白,可以看来源的第38题!如果还是有疑问,欢迎留言!
第7题 (来源:https://mp.weixin.qq.com/s/PYD9jzcbEtooZYvuuYMf_Q)
输出什么?
let person= {name:'hu'};
const member = [person];
person = null;
console.log(person);
可以对比下面输出什么?或许你就明白了
let person= {name:'hu'};
const member = [person];
person.name = 'fafa';
console.log(member);
来源的46题有解析,如果还有疑问,欢迎留言!
第8题(来源:https://mp.weixin.qq.com/s/PYD9jzcbEtooZYvuuYMf_Q)
输出什么?
const value ={number:10};
const multiply = ( x={...value} ) =>{
console.log(x.number *= 2);
};
multiply();
multiply();
multiply(value);
multiply(value);
注意两点:1 默认值 2 引用传值。解析可以参考来源的64题
第9题 (来源:https://www.cnblogs.com/donghezi/p/9742778.html)
function fn1(){
console.log(1);
}
function fn2(){
console.log(2);
}
fn1.call(fn2); //输出 1
fn1.call.call(fn2); //输出 2
输出什么?为什么?
首先需要好好理解call的原理,接着注意执行顺序,其实fn1.call.call(fn2) 就是 Function.call.call(fn2),结合实现源码,context就是fn2,this(即fn)就是call方法,最后执行context.fn就是执行fn2.call(),所以输出2
第10题 来源(京程一灯)
解析: