【发布时间】:2017-09-08 07:43:17
【问题描述】:
所以我喜欢这个 React 东西,我们有这个所谓的“无状态”函数来帮助我们构建一个“哑”组件。现在我想创建一个产生无状态函数的类。为什么您可能会问,我喜欢继承的想法,并希望“扩展”我的无状态函数基本功能,说我想添加一个辅助函数作为绑定到函数本身的静态变量。
我最终得到了这段代码
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()
为什么即使在render 函数中我也无法访问stateless.nanny,我可以看到this.nanny 可以访问? nanny 住在哪里?它是否绑定到render 函数?
EG:
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 的静态属性,对吧?
【问题讨论】:
-
如果您能给出一个更具体的案例,我们大家很容易以更好的方式帮助您。
-
我举个例子详细说明
-
试试
console.log(stateless)。 -
@ceving babeljs.io/repl/…
标签: javascript reactjs class static