JavaScript笔记——作用域

理解作用域

var self = this;

如果要在回调函数中使用变量,要使用self

作用域问题:

Js是单线程的,有消息队列机制

"use strict";

let a = 0;

setTimeout(() => {
  a = 1;
  console.log('a = 1');
}, 100);

console.log(a);

setTimeout(() => {
  console.log(a);
}, 100);

  1. 变量的生命周期
  2. 执行顺序

对象的作用域

"use strict";

function A() {
  const test = {};

  B(test);
  console.log(test);
}

function B(test) {
  test = {a: 1123};
  console.log(test);
}

A();

// { a: 1123 }
// {}
"use strict";

function A() {
  const test = {};

  B(test);
  console.log(test);
}

function B(test) {
  test.a = {a: 1123};
  console.log(test);
}

A();

// { a: { a: 1123 } }
// { a: { a: 1123 } }

指针指向问题,相当于:

"use strict";
var a = {}
var b = a
b = "123"

console.log("b", b)
console.log("a", a)

// b 123
// a {}

因为变量b在b = "123"时,已经不指向变量a了,而指向一个新的变量"123"

"use strict";

var a = {}
var b = a

b = "123"
b.c = '345'

console.log("b", b)
console.log("a", a)

// error
b.c = '345'
    ^
TypeError: Cannot create property 'c' on string '123'
    at Object.<anonymous> (/Users/simon/workspace/iPlayABC/cocos2dhtmlbase/public/games/book_pete_the_cat_and_his_magic_sunglasses/src/test.js:9:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

对比如下:

"use strict";
var a = {}
var b = a

b.c = '345'
b = "123"

console.log("b", b)
console.log("a", a)

// b 123
// a { c: '345' }

b.c = '345'时,其实是指向的变量a,所以是给变量a的属性c赋值。
接下来,b = "123"语句说明此时变量b指向了新的对象"123"

Show Comments