javascript 的 this , js 线程
1. this 知多少
以为自己对this 已经了解了,但是昨天看了一道题目,发现并非如此,先看代码
1 c = 999; 2 var c = 888; 3 console.log(this.c); //888 4 function b (x, y, c) { 5 c = 6; 6 arguments[2] = 10; 7 console.log(c); //10 8 console.log(this.c); //888 9 10 var c = 6; 11 console.log(c); //④ 12 console.log(this.c); //⑤ 13 } 14 b(1, 2, 3, 4);
在外部的c == var c == this.c == window.c . 那么在function b 里面的 this.c 为什么等于 window.c 呢? 查阅原来js 里面的this 指向当前的对象,那么function b 现在全局环境中运行,因此 this 是指向window 的。
那么我想改变this 的指向,怎么做呢?
1 c = 999; 2 var c = 888; 3 console.log(this.c); //888 4 function b (x, y, c) { 5 c = 6; 6 arguments[2] = 10; 7 console.log(c); //10 8 console.log(this.c); //888 9 10 var c = 6; 11 console.log(c); //④ 12 console.log(this.c); //⑤ 13 } 14 b(1, 2, 3, 4); 15 16 o = { 17 c :77 18 }; 19 20 o.b = b; 21 o.b();
这个时候,this 就指向o 了,输出结果也就不是888了 而是 77,可以验证。
2.JS单线程
var start = new Date(); setTimeout( function(){ var end = new Date(); console.log(end - start); }, 1000 ) while(new Date() - start < 2000);
这个结果应该是大于2000的。
3.一道容易错的
1 function a(){ return a; /*var b = 0;return b;*/} 2 console.log(new a() instanceof a);//false
因为a 是 return a ,那么 a instanceof a ,当然是错误的了。
function a (){}
var b = new a;
b instanceof a; //true 这个时候就是对的了
疯癫不成狂,有酒勿可尝;世间良辰美,终成水墨白。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步