读《You Don't Know JS Yet》新收获

634 阅读1分钟

最近在读YDKJSY,将新收获记录在这

全局变量原来是这样的

以前一直以为全局变量都是可以作为window的属性被访问的,今天才知道只有使用var,function声明的才通过window.xxx访问到,letconstclass等声明的不能被访问到

var one = 1;
let notOne = 2;
const notTwo = 3;
class notThree {}

console.log(window.one);       // 1
console.log(window.notOne);    // undefined
console.log(window.notTwo);    // undefined
console.log(window.notThree);  // undefined

let声明的变量不会影响window属性

window.something = 42;

let something = "Kyle";

console.log(something);       // "Kyle"
console.log(window.something) // 42

window.name是一个预定义的全局属性,用来设置/获取窗口名称,无论设置何值,会通过ToString强转为string

var name = 42;

console.log(typeof name, name);
// string 42

要想使用非string类型的name,需要使用let声明。

全局对象可以如此获取

const theGlobalScopeObject =
    (typeof globalThis !== "undefined") ? globalThis :
    (typeof global !== "undefined") ? global :
    (typeof window !== "undefined") ? window :
    (typeof self !== "undefined") ? self :
    (new Function("return this"))();

use strict原来还有这作用

函数表达式内的函数名原来是只读的

var askQuestion = function ofTheTeacher() {
    "use strict";
    ofTheTeacher = 42;   // TypeError:Assignment to constant variable

    //..
};

askQuestion();

在严格模式下ofTheTeacher是只读的,

let原来还有这波操作

使用let声明的变量不能再次被声明,已声明的变量也不能使用let再次声明

var studentName = "Frank";
let studentName = "Suzy"; // SyntaxError: Identifier 'studentName' has already been declared
let studentName = "Frank";
var studentName = "Suzy"; // SyntaxError: Identifier 'studentName' has already been declared