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

精读《Classes, Complexity, and Functional Programming》 #19

Closed
ascoders opened this issue Jun 18, 2017 · 1 comment
Closed

精读《Classes, Complexity, and Functional Programming》 #19

ascoders opened this issue Jun 18, 2017 · 1 comment

Comments

@ascoders
Copy link
Owner

文章地址:https://medium.com/@kentcdodds/classes-complexity-and-functional-programming-a8dd86903747
到底怎么使用js才能使维护性更持久?

@ascoders ascoders mentioned this issue Jun 19, 2017
65 tasks
@ascoders
Copy link
Owner Author

ascoders commented Jun 23, 2017

本文作者认为,class 带来的困惑主要在于 this,这主要因为成员函数会挂到 prototype 下,虽然多个实例共享了引用,但因此带来的隐患就是 this 的不确定性。js 有许多种 this 丢失情况,比如 隐式绑定 别名丢失隐式绑定 回调丢失隐式绑定 显式绑定 new绑定 箭头函数改变this作用范围 等等。

由于在 prototype 中的对象依赖 this,如果 this 丢了,就访问不到原型链,不但会引发报错,在写代码时还需要注意 this 的作用范围是很头疼的事。因此作者有如下解决方案:

function getPerson(initialName) {
  let name = initialName
  const person = {
    setName(strName) {
      name = strName
    }
  }
  return person
}

由此生成的 person 对象不但是个简单 object,由于没有调用 this,也不存在 this 丢失的情况。

这个观点我是不认可的。首先做法没有问题,代码逻辑也正确,也解决了 this 存在的原型链访问丢失问题,但这并不妨碍使用 this。我们看以下代码:

class Person {
  setName = (name) => {
    this.name = name
  }
}

const person = new Person()
const setName = person.setName
setName("Jane Doe")
console.log(person)

这里用到了 this,也产生了别名丢失隐式绑定,但 this 还能正确访问的原因在于,没有将 setName 的方法放在原型链上,而是放在了每个实例中,因此无论怎么丢失 this,也仅仅丢失了原型链上的方法,但 this 无论如何会首先查找其所在对象的方法,只要方法不放在原型链上,就不用担心丢失的问题。

至于放在原型链上会节约多个实例内存开销问题,函数式也无法避免,如果希望摆脱 this 带来的困扰,class 的方式也可以解决问题。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant