Introduction to ES6 (1)
Block-level scope-let command, const command
-Variables declared with the let command will not be promoted
(function(){
if(true){
let a = 5;
}
console.log(a); //报错
})
-Variables declared with the const command must be assigned at the time of declaration
const a; //报错
-If a variable declared with the const command is assigned to an object, the address it points to cannot be changed, and the properties of the object cannot be controlled.
const a = {};
a.name = 'Tom';//正确
a = {name: 'Tom'};//报错
If you need to freeze the object, you need to use the Object.freeze method
var obj = Object.freeze({});
obj.age = 18;//常规模式下无效,严格模式下报错
To freeze the object itself and the properties of the object, you can use the following method
var constantize = (obj) => {
Object.freeze(obj);
Object.keys(obj).forEach( (key, i) => {
if ( typeof obj[key] === 'object' ) {
constantize( obj[key] );
}
});
};
-ES6 Six methods of declaring variables: var command, function command, let command, const command, import command, class command
-Method to get the top-level object of the page
// 方法一
(typeof window !== 'undefined'
? window
: (typeof process === 'object' &&
typeof require === 'function' &&
typeof global === 'object')
? global
: this);
// 方法二
var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};