所以我喜欢这个 React 东西,我们有这个所谓的“无状态”函数来帮助我们构建一个“哑”组件。现在我想创建一个产生无状态函数的类。为什么您可能会问,我喜欢继承的想法并希望“扩展”我的无状态函数基本功能,我说我想添加一个辅助函数作为绑定(bind)到函数本身的静态变量。
我得到了这段代码
class Stateless {
constructor() {
return this.render.bind(this)
}
nanny() {
// do something
}
render(props) {
// yeay! a stateless function!
// plus i can access nanny by using this.nanny()
}
}
当我扩展它时,我可以看到继承工作正常。 但是,如果我初始化类:
const stateless = new Stateless()
为什么我不能访问 stateless.nanny
,即使在 render
函数中我可以看到 this.nanny
是可访问的? 保姆
住在哪里?它是否绑定(bind)到 render
函数?
如:
class Stateless {
constructor() {
return this.render.bind(this)
}
nanny() {
console.log('foo')
return true
}
render(props) {
console.log(this.nanny()) // -> returns 'foo'
return 'JSX'
// this should return a JSX
}
}
const stateless = new Stateless() // -> stateless IS a function
stateless()
// 'foo'
// true
// JSX
stateless.nanny
// undefined
当我调用 this
时,显然在 render
中,那里有保姆。但是当我
到外面去,保姆不见了。我认为 nanny
应该是 stateless
的静态属性,对吧?
最佳答案
如果您从构造函数返回对象 - new
将返回该对象而不是正在构造的类的实例 (more info)。
因此行
const stateless = new Stateless()
将分配给 this.render.bind(this)
的 stateless
变量结果 - 这是对 Stateless 类的方法(函数)的引用,即 不是无状态的实例。因此 stateless.nanny
没有意义 - 因为函数 render
没有定义这样的属性。另一方面,直接调用绑定(bind)的 render
函数 - 产生预期的结果。
总而言之——我强烈不建议你从构造函数返回任何东西(除非你正在处理一些非常奇怪的要求,比如控制实例数量等)。它使代码难以理解和维护。
关于javascript - 返回函数的 JS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46111220/