“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 7 天, 点击查看活动详情 ”
前言
5道js测试题检验你的基础是否扎实,希望也会对大家有所帮助。
第一题
下面代码的输出结果是什么?
window.n='widonw name'
let obj={
n:'obj name',
sayName(){
console.log(this.n)
}
}
let fn=obj.sayName();
fn()
结果输出: widonw name 详细解答:谁调用this就之乡谁的原则, fn()是window在调用,因此输出 widonw name
第二题
下面代码的输出结果是什么?
window.n='widonw name'
let obj={
n:'obj name',
sayName:()=>{
console.log(this.n)
}
}
obj.sayName()
结果输出: widonw name 详细解答: 谁调用this就之乡谁的原则, 并且箭头函数中没有this。 因此指向window,输出widonw name
第三题
下面代码的输出结果是什么?
class A {
constructor() {
this.name = "A";
}
sayName() {
console.log(this.name);
}
}
class B extends A {
constructor() {
super();
this.name = "B";
}
}
let obj = new B();
console.log(obj.sayName());
输出结果:B
详细解答:在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
第四题
下面代码的输出结果是什么?
Promise.reject('error')
.then(()=>{console.log('success1')},()=>{console.log('error1')})
.then(()=>{console.log('success2')},()=>{console.log('error2'))
输出结果: 先输出‘error1’再输出‘success2’
详细解答:这里考的是primose,promise 有 3 种状态:pending、fulfilled 或 rejected 状态一旦改变就不会发生变化
promise 每次调用.then或者.catch 都会返回一个新的 promise,从而实现了链式调用。
第五题
下面代码的输出结果是什么?
function getSomeThing(){
setTimeout(function()=>{
return 'hello'
})
}
let something=getSomeThing()
console.log(something)
输出结果:undefined 详细解答: 这里的return 是setTimeOut函数中的返回,而不是getSomeThing函数中的返回值
结束语
希望大家能够喜欢我的文章,我真的很用心在写,也希望通过文章认识更多志同道合的朋友。
最后伙伴们,如果喜欢我的可以给点一个小小的赞👍或者关注➕都是对我最大的支持。