JavaScript/变量提升:修订间差异
来自康健生活
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” 标签:ReplaceText 移动版编辑 移动版网页编辑 |
|||
| (未显示同一用户的3个中间版本) | |||
| 第1行: | 第1行: | ||
== 引言 == | == 引言 == | ||
=== 提升 === | === 提升 === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
for(var i=0;i<5; i++){ | for(var i=0;i<5; i++){ | ||
console.info(i); | console.info(i); | ||
| 第12行: | 第12行: | ||
3 | 3 | ||
4 | 4 | ||
5</pre>}} | 5</pre>}}}} | ||
=== 避免提升 === | === 避免提升 === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
;(function(){ | ;(function(){ | ||
for(var i=0;i<5; i++){ | for(var i=0;i<5; i++){ | ||
| 第29行: | 第30行: | ||
Uncaught ReferenceError: i is not defined | Uncaught ReferenceError: i is not defined | ||
at <anonymous>:6:13</pre>}}}} | at <anonymous>:6:13</pre>}}}} | ||
== 变量提升 == | |||
字节的一道面试题,这道题没什么可讲的,考察的是作用域和变量提升 | |||
{{Double-columns|<syntaxhighlight | |||
lang="javascript"> | |||
window.name = 'ByteDance'; | |||
function A () { | |||
this.name = 123; | |||
} | |||
A.prototype.getA = function(){ | |||
console.log(this); | |||
return this.name + 1; | |||
} | |||
let a = new A(); | |||
let funcA = a.getA; | |||
funcA(); | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
ByteDance1 | |||
</pre>}}}} | |||
2026年11月26日 (四) 10:08的最新版本
引言
提升
for(var i=0;i<5; i++){
console.info(i);
}
console.log(i);
0 1 2 3 4 5
避免提升
;(function(){
for(var i=0;i<5; i++){
console.info(i);
}
})();
console.log(i);
0
1
2
3
4
Uncaught ReferenceError: i is not defined
at <anonymous>:6:13变量提升
字节的一道面试题,这道题没什么可讲的,考察的是作用域和变量提升
window.name = 'ByteDance';
function A () {
this.name = 123;
}
A.prototype.getA = function(){
console.log(this);
return this.name + 1;
}
let a = new A();
let funcA = a.getA;
funcA();
ByteDance1
No categories