Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《你不知道的javascript(上)》附录以及个人理解 #12

Open
qunzi0214 opened this issue Oct 10, 2020 · 0 comments
Open

《你不知道的javascript(上)》附录以及个人理解 #12

qunzi0214 opened this issue Oct 10, 2020 · 0 comments
Labels
read book 读书笔记

Comments

@qunzi0214
Copy link
Owner

qunzi0214 commented Oct 10, 2020

第一部分附录

动态作用域

function foo() {
  console.log(a); // 2
}

function bar() {
  var a = 3;
  foo();
}

var a = 2;

bar();

如果javascript具有动态作用域,则应该在调用处获得变量 a 的值(3)。而javascript中的 this 的机制和动态作用域很像

Traceur编译器

实际上,谷歌维护的 Traceur 编译器会把块级作用域编译成 try...catch (在es5或以下环境)

显式 let 声明

非官方标准

let (a = 2) {
  console.log(a); // 2
}

console.log(a); // ReferenceError

第二部分附录

es6 class 解决的问题

class Person {
  constructor(sex) {
    this.sex = sex;
  }

  speak() {
    console.log(`hi, i'm a person`);
  }
}

class Rango extends Person {
  constructor(sex, age, name) {
    super(sex);
    this.age = age;
    this.name = name;
  }

  speak() {
    super.speak();
    console.log(`hi, i'm ${this.name}`);
  }
}

const r = new Rango('male', 18, 'Rango');

r.speak();
  1. 不会再引用杂乱的prototype
  2. 可以通过 super 来实现相对多态
  3. 可以通过 extends 很自然的扩展子类型,甚至是内置对象

es6 class 的陷阱

本质上是 prototype 机制的语法糖,子类仍然不是父类的复制,而是委托。同时 super 的绑定机制存在问题(待测试)。

一些个人理解

关于正确使用this机制

书中提倡正确包涵 this 机制(比如通过bind显式声明),而不是使用箭头函数等方式来混淆 this 绑定规则和词法作用域。个人觉得大同小异...

关于类风格和委托风格

书中对于强行将 javascript 的对象委托机制实现为类风格提出了批评。考虑到目前绝大多数前端框架仍然会使用类风格来编写程序,此处存疑,还需要后续知识储备更完善后重新判断

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
read book 读书笔记
Projects
None yet
Development

No branches or pull requests

1 participant