Open xgqfrms opened 5 years ago
"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;
"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
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
区别
是否存在 hoisting
作用域不同
能否重复声明
能否重新赋值
声明时否要初始化