Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一些有意思的JS题目 #18

Open
YutHelloWorld opened this issue Mar 8, 2018 · 1 comment
Open

一些有意思的JS题目 #18

YutHelloWorld opened this issue Mar 8, 2018 · 1 comment

Comments

@YutHelloWorld
Copy link
Owner

YutHelloWorld commented Mar 8, 2018

在此摘录汇总一些从社区看到的文章、面经中的比较有意思的JS题目~

实例原型

Function.prototype.a = 'a';
Object.prototype.b = 'b';
function Person(){};
var p = new Person();
console.log('p.a: '+ p.a); // p.a: undefined
console.log('p.b: '+ p.b); // p.b: b

解释:实例p的原型链由Person、Object构成,没有Function

this

const person = {
  name: 'menglinghua',
  say: function (){
    return function (){
      console.log(this.name);
    };
  }
};
person.say()(); // ''(空字符串)

解释:this指向window,window.name===''

const person = {
  name: 'menglinghua',
  say: function (){
    return () => {
      console.log(this.name);
    };
  }
};
person.say()(); 

解释:箭头函数将this绑定到了声明域,指向person

队列

setTimeout(() => console.log('a'), 0);
var p = new Promise((resolve) => {
  console.log('b');
  resolve();
});
p.then(() => console.log('c'));
p.then(() => console.log('d'));
console.log('e');
// 结果:b e c d a

解释:任务队列优先级:promise.Trick()>promise的回调>setTimeout>setImmediate

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})

结果: 1 7 6 8 2 4 3 5 9 11 10 12
解释:原文地址,https://juejin.im/post/59e85eebf265da430d571f89#heading-4

数值类型转换

Number('') // 0
parseInt('') // NaN
Number('123abc') // NaN
parseInt('123abc') // 123
@vivinbear
Copy link

const person = {
name: 'menglinghua',
say: function (){
return function (){
console.log(this.name);
};
}
};
person.say()(); // 这里的输出结果需要根据环境来区分,浏览器下,是空字符串,而node中时undefined.因为浏览器环境下,window是有name属性的,name的值是空,所以会输出空字符串
其余的很棒

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants