xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Learn-JavaScript-with-MDN 系列文章: 01. var & let & const 对比

Learn-JavaScript-with-MDN 系列文章: 01. var & let & const 对比

var & let & const 区别

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const




var, let, const 区别 All In One

  1. 是否存在 hoisting

var 存在 hoisting; let, const 不存在 hoisting;

  1. 作用域不同

var 是全局scope或函数 scope; let, const 是 block scope;

全局作用域里面定义的 const, let 不会挂载到 window 对象上面;
全局作用域里面定义的 var 会挂载到 window 对象上面;

const log = console.log;

var a = 1;
log(`a =`, window.b);

let b = 1;
log(`b =`, window.b);

const c = 1;
log(`c =`, window.c);

  1. 能否重复声明

var 可以重复声明; let, const 不可以重复声明

  1. 能否重新赋值

var 可以重新赋值, let 可以重新赋值; const 不可以重新赋值, 但是如果是 Object 可以,修改 Object 的属性值;

  1. 声明时否要初始化

var 可选初始化; let 可选初始化, 但是存在 TDZ(暂时死区); const 声明时必须初始化;

未经授权,禁止转载

版权所有 copyright © xgqfrms 2019-forever

原文链接: https://www.cnblogs.com/xgqfrms/p/11421323.html

scope & hoisting

https://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

https://repl.it/@xgqfrms/Function-hoisting-greater-var-hoisting

https://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting

function hoisting

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-05-30
 * @modified
 *
 * @description function-hoisting.js
 * @augments
 * @example
 * @link
 *
 */

const log = console.log;

var a = 1;
function b() {
  a = 10;
  log(`local a`, a)
  return;
  // function hoisting 优先级大于 variable hoisting
  function a() {}
}

b();
log(`global a`, a);

// local a 10
// global a 1



const log = console.log;

// define "a" in global scope
var a = 1;

function b() {
  // define "a" in local scope
  var a ;
  // assign function to a
  a = function () {};
  // var a = function () {};
  // overwrites local variable "a"
  a = 10;
  log(`local a`, a);
  return;
}

b();
// log global variable "a"
log(`global a`, a);

// local a 10
// global a 1

js var hoisting

  1. function

  2. var

https://www.sitepoint.com/5-typical-javascript-interview-exercises/

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2019-08-27 22:54  xgqfrms  阅读(251)  评论(9编辑  收藏  举报