xgqfrms / learning-javascript-with-mdn

Learning JavaScript with MDN / 使用 MDN 学习 JavaScript
https://learning-javascript-with-mdn.xgqfrms.xyz
MIT License
1 stars 0 forks source link

01. var & let & const #1

Open xgqfrms opened 5 years ago

xgqfrms commented 5 years ago

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

区别

  1. 是否存在 hoisting

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

  2. 作用域不同

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

  3. 能否重复声明

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

  4. 能否重新赋值

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

  5. 声明时否要初始化

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

xgqfrms commented 5 years ago

demos

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2019-08-27
 * @modified
 *
 * @description Learn-JavaScript-with-MDN (var & let & const)
 * @augments
 * @example
 * @link
 *
 */

let log = console.log;
xgqfrms commented 5 years ago

image

xgqfrms commented 4 years ago

https://github.com/xgqfrms/CV/issues/54#issuecomment-636577090

xgqfrms commented 4 years ago
"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-05-31
 * @modified
 *
 * @description
 * @augments
 * @example
 * @link
 *
 */

const log = console.log;

function Foo() {
  Foo.a = function() {
    log(1)
  }
  // TypeError: Cannot set property 'a' of undefined
  this.a = function() {
    log(2)
  }
}

// Foo.a();
// TypeError: Foo.a is not a function

// Foo().a();
// TypeError: Cannot set property 'a' of undefined

// Foo.prototype.a = function() {
//   log(3)
// }

// Foo.a();

// Foo.a();
// TypeError: Foo.a is not a function

// Foo.a = function() {
//   log(4)
// }

// Foo.a();

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-05-31
 * @modified
 *
 * @description function 静态方法, 原型方法, 示例方法(调用上下文)
 * @augments
 * @example 4, 2, 1
 * @link
 *
 */

const log = console.log;

function Foo() {
  // static method
  // 静态方法
  Foo.a = function() {
    log(1)
  }
  // 实例方法
  this.a = function() {
    log(2)
  }
}

// Foo.a();
// TypeError: Foo.a is not a function

// Foo().a();
// TypeError: Cannot set property 'a' of undefined

// 原型方法
Foo.prototype.a = function() {
  log(3)
}
// 原型链, 实例方法上找不到, 才会向原型链上找(优先级问题)
Foo.prototype.b = function() {
  log(`b`)
}

// Foo.a();

// Foo.a();
// TypeError: Foo.a is not a function

// 覆写, 构造函数的静态方法
Foo.a = function() {
  log(4)
}

// Foo 此时没有被调用, Foo 函数内部的属性方法没有初始化
Foo.a();
// 4

// Foo 此时被调用, Foo 函数内部的属性方法初始化, 原型链建立
const obj = new Foo();

// 实例方法
obj.a();
// 2
// 实例静态方法, 覆盖了同名的类静态方法
Foo.a();
// 1

// 原型链, 实例方法上找不到, 才会向类原型链上找(优先级问题)
obj.b();
// b