暂时性死区

只要块级作用域存在let命令,它所声明的变量就“绑定”这个区域,不再受外部的影响。这么说可能有些抽象,举个例子:

  1. var temp = 123;
  2. if(true) {
  3. console.log(temp);
  4. let temp;
  5. }
  6. 结果:
  7. > ReferenceError: temp is not defined

在代码块内,使用let声明变量之前,该变量都是不可用的。在语法上,称为“暂时性死区”。(temporal dead zone)
ES6规定暂时性死区和let、const语句不出现变量提升,主要是为了减少运行时错误,防止在变量声明前就使用这个变量,从而导致意料之外的行为。

call和apply方法

这两个方法都可以改变一个函数的上下文对象,只是接受参数的方式不一样。
call接收的是逗号分隔的参数。
apply接收的是参数列表。
相信你肯定看到过这样的代码:

  1. var arr = [1, 2, 3];
  2. var max = Function.prototype.apply.call(Math.max, null, arr);
  3. console.log(max); // 3

那么对这段代码怎么理解呢?

  • 1.将Function.prototype.apply看成一个整体

    1. (Function.prototype.apply).call(Math.max, null, arr)
  • 2.func.call(context, args)可以转化为context.func(args)

所以代码被转换为:

  1. Math.max.apply(undefined, arr)

基本上到这一步已经没必要去解释了。
那么你有没有试过将call和apply互换位置呢?

  1. var arr = [1, 2, 3];
  2. var max = Function.prototype.call.apply(Math.max, null, arr);
  3. console.log(max); // -Infinity

为什么的它的输出结果为-Infinity呢?
因为apply的第二参数必须为数组,这里并不是,所以参数不能正确的传递给call函数。
根据func.apply(context, args)可以转化为context.func(args)。所以被转化成了Math.max.call(), 直接调用则会输出-Infinity。
如果想要正确调用,则应这样书写:

  1. var arr = [1, 2, 3];
  2. var max = Function.prototype.call.apply(Math.max, arr);
  3. console.log(max); // 3

为了巩固以上内容,且看一个面试题:

  1. var a = Function.prototype.call.apply(function(a){return a;}, [0,4,3]);
  2. alert(a);

分析弹出的a值为多少?

  1. // 将call方法看成一个整体
  2. (Function.prototype.call).apply(function(a){return a;}, [0,4,3]);
  3. // func.apply(context, args)可以转化为context.func(...args)
  4. (function(a){return a;}).call(0, 4, 3);
  5. // 所以结果很明显,输出4

Proxy对象

作用:用来自定义对象中的操作。

  1. let p = new Proxy(target, handler)

target 代表需要添加代理的对象,handler 用来自定义对象中的操作,比如可以用来自定义 set 或者 get 函数。
且看一个的小栗子:

  1. // onChange 即要进行的监听操作
  2. var watch = (object, onChange) => {
  3. const handler = {
  4. // 如果属性对应的值为对象,则返回一个新的Proxy对象
  5. get(target, property, receiver) {
  6. try {
  7. return new Proxy(target[property], handler);
  8. } catch (err) {
  9. return Reflect.get(target, property, receiver);
  10. }
  11. },
  12. // 定义或修改对象属性
  13. defineProperty(target, property, descriptor) {
  14. onChange('define',property);
  15. return Reflect.defineProperty(target, property, descriptor);
  16. },
  17. // 删除对象属性
  18. deleteProperty(target, property) {
  19. onChange('delete',property);
  20. return Reflect.deleteProperty(target, property);
  21. }
  22. };
  23. return new Proxy(object, handler);
  24. };
  25. // 测试对象
  26. var obj = {
  27. name: 'bjw',
  28. age: 22,
  29. child: [1, 2, 3]
  30. }
  31. // 对象代理
  32. var p = watch(obj1, (type, property) => {
  33. console.log(`类型:${type}, 修改的属性:${property}`)
  34. });
  35. p.name = 'qwe'
  36. 类型:define, 修改的属性:name
  37. "qwe"
  38. p.child
  39. Proxy {0: 1, 1: 2, 2: 3, length: 3}
  40. p.child.push(4)
  41. 类型:define, 修改的属性:3
  42. 类型:define, 修改的属性:length
  43. 4
  44. p.child.length = 2
  45. 类型:define, 修改的属性:length
  46. 2
  47. p.child
  48. Proxy {0: 1, 1: 2, length: 2}

如果关注Vue进展的话,可能已经知道Vue3.0中将通过Proxy来替换原来的Object.defineProperty来实现数据响应式。之所以要用Proxy替换原来的API原因在于Proxy无需一层层递归为每个属性添加代理,一次即可完成以上操作。性能上更好,并且原本的实现有一些数据更新不能监听到,但Proxy可以完美监听到任何方式的数据改变,相信通过上面的例子已经能够感受到Proxy带来的优势了。唯一的缺点可能就是浏览器兼容性不太好了。

Reflect对象

为什么要有这样一个对象?

  • 用一个单一的全局对象去存储这些方法,能够保持其他的JavaScript代码整洁、干净。(不然的话得通过原型链调用)
  • 将一些命令式的操作delete、in使用函数代替,目的是为了让代码更好维护,避免出现更多的保留字。

Reflect对象拥有以下静态方法:

  1. Reflect.apply
  2. Reflect.construct
  3. Reflect.defineProperty
  4. Reflect.deleteProperty
  5. Reflect.enumerate // 废弃的
  6. Reflect.get
  7. Reflect.getOwnPropertyDescriptor
  8. Reflect.getPrototypeOf
  9. Reflect.has
  10. Reflect.isExtensible
  11. Reflect.ownKeys
  12. Reflect.preventExtensions
  13. Reflect.set
  14. Reflect.setPrototypeOf

具体函数细节:

Reflect.apply(target, this, arguments)

  1. // target:目标函数
  2. // this:绑定的上下文对象
  3. // arguments:函数的参数列表
  4. Reflect.apply(target, this, arguments)
  5. const arr = [2, 3, 4, 5, 6];
  6. let max;
  7. // ES6
  8. max = Reflect.apply(Math.max, null, arr)
  9. // ES5
  10. max = Math.max.apply(null, arr);
  11. max = Function.prototype.apply.call(Math.max, null, arr);

Reflect.construct(target, argumentsList[, newTarget])

  1. // 这个方法,提供了一种新的不使用new来调用构造函数的方法
  2. function A(name) {
  3. console.log('Function A is invoked!');
  4. this.name = name;
  5. }
  6. A.prototype.getName = function() {
  7. return this.name;
  8. };
  9. function B(age) {
  10. console.log('Function B is invoked!');
  11. this.age = age;
  12. }
  13. B.prototype.getAge = function() {
  14. return this.age;
  15. };
  16. // 测试 (这两种是一致的)
  17. var tom = new A('tom');
  18. var tom = Reflect.construct(A, ['tom']);
  19. // jnney继承了A的实例属性,同时继承了B的共享属性
  20. // 简单来说,A构造函数被调用,但是 jnney.__proto__ === B.prototype
  21. var jnney = Reflect.construct(A, ['jnney'], B);

Reflect.defineProperty(target, propertyKey, attributes) 这个方法和Object.definePropperty(属性定义失败,会抛出一个错误,成功则返回该对象)相似,不过Reflect.defineProperty(属性定义失败,返回false,成功则返回true)返回的是一个Boolean值。

  1. let obj = {};
  2. let obj1 = Object.defineProperty(obj, 'name', {
  3. enumerable: true,
  4. value: 'bjw'
  5. });
  6. // 这里会返回false 因为我们上面定义name这个属性是不可修改的,
  7. // 然后我们又在这里修改了name属性,所以修改失败返回值为false
  8. let result1 = Reflect.defineProperty(obj, 'name', {
  9. configurable: true,
  10. enumerable: true,
  11. value: 'happy'
  12. });
  13. console.log(result1); // false

Reflect.deleteProperty(target, propertyKey)

  1. let obj = {
  2. name: 'dreamapple',
  3. age: 22
  4. };
  5. let r1 = Reflect.deleteProperty(obj, 'name');
  6. console.log(r1); // true
  7. let r2 = Reflect.deleteProperty(obj, 'name');
  8. console.log(r2); // true
  9. let r3 = Reflect.deleteProperty(Object.freeze(obj), 'age');
  10. console.log(r3); // false

Reflect.get(target, propertyKey[, receiver]) >
> Reflect.set(target, propertyKey, value[, receiver]) 这个方法用来读取/设置一个对象的属性,target是目标对象,propertyKey是我们要读取的属性,receiver是可选的,如果propertyKey的getter函数里面有this值,那么receiver就是这个this所代表的上下文。 Reflect.getOwnPropertyDescriptor(target, propertyKey) 这个方法与Object.getOwnPropertyDescriptor方法类似,其中target是目标对象,propertyKey是对象的属性,如果这个属性存在属性描述符的话就返回这个属性描述符;如果不存在的话,就返回undefined。(如果第一个参数不是对象的话,那么Object.getOwnPropertyDescriptor会将这个参数强制转换为对象,而方法 Reflect.getOwnPropertyDescriptor会抛出一个错误。)

  1. var obj = {age: 22}
  2. Reflect.getOwnPropertyDescriptor(obj, 'age')
  3. {value: 22, writable: true, enumerable: true, configurable: true}

Reflect.getPrototypeOf(target) >
> Reflect.setPrototypeOf(target, prototype) 这个方法与Object.getPrototypeOf方法是一样的,都是返回一个对象的原型,也就是内部的[[Prototype]]属性的值。
Reflect.setPrototypeOf与Object.setPrototypeOf方法的作用是相似的,设置一个对象的原型,如果设置成功的话,这个对象会返回一个true;如果设置失败,这个对象会返回一个false。 Reflect.has(target, propertyKey) 这个方法相当于ES5的in操作符,就是检查一个对象上是否含有特定的属性;我们继续来实践这个方法:

  1. function A(name) {
  2. this.name = name || 'dreamapple';
  3. }
  4. A.prototype.getName = function() {
  5. return this.name;
  6. };
  7. var a = new A();
  8. console.log('name' in a); // true
  9. console.log('getName' in a); // true
  10. let r1 = Reflect.has(a, 'name');
  11. let r2 = Reflect.has(a, 'getName');
  12. console.log(r1, r2); // true true

Reflect.isExtensible(target) 这个函数检查一个对象是否是可以扩展的,也就是是否可以添加新的属性。(要求target必须为一个对象,否则会抛出错误)

  1. let obj = {};
  2. let r1 = Reflect.isExtensible(obj);
  3. console.log(r1); // true
  4. // 密封这个对象
  5. Object.seal(obj);
  6. let r2 = Reflect.isExtensible(obj);
  7. console.log(r2); // false

模块化

使用模块化,可以为我们带来以下好处:

  • 解决命名冲突
  • 提供复用性
  • 提高代码可维护性

    立即执行函数

    在早期,使用立即执行函数实现模块化,通过函数作用域解决了命名冲突、污染全局作用域的问题。

    AMD 和 CMD

    这两种实现方式已经很少见到,具体的使用方式如下:

    1. // AMD
    2. define(['./a', './b'],function(a, b){
    3. // 模块加载完毕可以使用
    4. a.do();
    5. b.do();
    6. });
    7. // CMD
    8. define(function(require, exports, module){
    9. // 加载模块
    10. var a = require('./a');
    11. });

    CommonJS

    CommonJS最早是Node在使用,目前可以在Webpack中见到它。

    1. // a.js
    2. module.exports = {
    3. a: 1
    4. }
    5. // or
    6. exports.a = 1;
    7. // 在b.js中可以引入
    8. var module = require('./a');
    9. module.a // log 1

    难点解析:

    1. // module 基本实现
    2. var module = {
    3. id: 'xxx',
    4. exports: {}
    5. }
    6. var exports = module.exports;
    7. // 所以,通过对exports重新赋值,不能导出变量

    ES Module

    ES Module 是原生实现模块化方案。

    1. // 导入模块
    2. import xxx form './a.js';
    3. import { xxx } from './b.js';
    4. // 导出模块
    5. export function a(){}
    6. // 默认导出
    7. export default {};
    8. export default function(){}

    ES Module和CommonJS区别

  • CommonJS支持动态导入,也就是require(${path}/xx.js),ES Module不支持

  • CommonJS是同步导入,因为用于服务器端,文件都在本地,同步导入即使卡住主线程影响也不大。而ES Module是异步导入,因为用于浏览器,需要下载文件,采用同步导入会对渲染有很大影响
  • CommonJS在导出时都是值拷贝,就算导出值变了,导入的值也不会改变。如果想更新值,必须重新导入一次。但是ES Module采用实时绑定的方式,导入导出的值都指向同一个内存地址,所以导入值会跟导出值变化
  • ES Module 会编译成 require/exports 来执行的

    手写简单版本的Promise

  1. const PENDING = 'pending';
  2. const RESOLVED = 'resolved';
  3. const REJECTED = 'rejected';
  4. function MyPromise(fn) {
  5. const _this = this;
  6. _this.state = PENDING;
  7. _this.value = null;
  8. _this.resolvedCallbacks = [];
  9. _this.rejectedCallbacks = [];
  10. // resolve函数
  11. function resolve(value) {
  12. if (_this.state === PENDING) {
  13. _this.state = RESOLVED;
  14. _this.value = value;
  15. _this.resolvedCallbacks.map(cb => cb(_this.value));
  16. }
  17. }
  18. // rejected函数
  19. function reject(value) {
  20. if (_this.state === PENDING) {
  21. _this.state = REJECTED;
  22. _this.value = value;
  23. _this.rejectedCallbacks.map(cb => cb(_this.value));
  24. }
  25. }
  26. // 当创建对象的时候,执行传进来的执行器函数
  27. // 并且传递resolve和reject函数
  28. try {
  29. fn(resolve, reject);
  30. } catch (e) {
  31. reject(e);
  32. }
  33. }
  34. // 为Promise原型链上添加then函数
  35. MyPromise.prototype.then = function (onFulfilled, onRejected) {
  36. const _this = this;
  37. onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
  38. onRejected = typeof onRejected === 'function' ? onRejected : r => {
  39. throw r;
  40. }
  41. if (_this.state === PENDING) {
  42. _this.resolvedCallbacks.push(onFulfilled);
  43. _this.rejectedCallbacks.push(onRejected);
  44. }
  45. if (_this.state === RESOLVED) {
  46. onFulfilled(_this.value);
  47. }
  48. if (_this.state === REJECTED) {
  49. onRejected(_this.value);
  50. }
  51. return _this;
  52. }
  53. // 测试
  54. new MyPromise(function (resolve, reject) {
  55. setTimeout(() => {
  56. resolve('hello');
  57. }, 2000);
  58. }).then(v => {
  59. console.log(v);
  60. }).then(v => {
  61. console.log(v + "1");
  62. })