我正在使用Hapi.JS在Node中构建应用程序。
我有一个用于身份验证插件的类,它给我带来各种各样的问题。当我尝试this
从类的方法中进行引用时,出现一条错误消息,this
即未定义。为什么会这样呢?
摘录:
class OAuth {
constructor () {}
register (server, err, next) {
this.server = server;
this.registerRoutes();
}
registerRoutes () {
console.log(this.server.route);
this.server.route([
{
method: 'POST',
path: '/oauth/token',
config: {
auth: false,
handler: function(request,reply){
console.log("test");
reply("test");
}
}
},
{
method: 'GET',
path: '/test',
config: {
auth: false,
handler: function(request,reply){
console.log("test");
reply("test");
}
}
}
]);
}
}
module.exports = new OAuth();
在其他地方,这称为:
const oauth = require('./oauth');
oauth.register(server);
每次调用寄存器函数时,都会收到此错误:
TypeError: Cannot set property 'server' of undefined
为什么我的实例不起作用?
带有babel的ES6类不会this
为您自动绑定。自class
引入以来,这是一个普遍的误解。有多种解决方法。
使用ES7。Babel有一个实验性的(截至本文)类属性插件。
class OAuth {
constructor () {}
register = (server, err, next) => {
this.server = server
this.registerRoutes()
}
registerRoutes = () => {}
}
这是如何运作的?当您将箭头功能与class-properties插件一起使用时,它会转换为如下所示的内容,并在您使用class
语法时按预期进行绑定。
var OAuth = function OAuth() {
var _this = this;
_classCallCheck(this, OAuth);
this.register = function (server, err, next) {
_this.server = server;
_this.registerRoutes();
};
this.registerRoutes = function () {};
}
将类属性绑定到构造函数中
class OAuth {
constructor () {
// `this` is the OAuth instance in the constructor
this.register = this.register.bind(this)
this.registerRoutes = this.registerRoutes.bind(this)
}
register (server, err, next) {
// `this` is the global object.. NOT!
// after binding in the constructor, it's the OAuth instance ^_^
// provided you use `new` to initialize your instance
this.server = server
this.registerRoutes()
}
registerRoutes () {}
}
使用createClass
from react,它将为您完成绑定。注意,我们仅将react用于其class属性绑定魔术。我们没有创建反应组件。
import React from 'react'
const OAuth = React.createClass({
register (server, err, next) {
this.server = server
this.registerRoutes()
}
registerRoutes () {}
})
仅autoBind
在react-class中使用。在这里,我们使用ES6 +类语法制作了一个react组件,只是为了使用该autoBind
方法。我们没有用componentWillMount
,render
等,其提供有反应的组分。
import { autoBind } from 'react-class'
class OAuth extends React.Component {
constructor(props) {
super(props)
autoBind(this)
}
register (server, err, next) {
this.server = server
this.registerRoutes()
}
registerRoutes () {}
}
滚动自己的类属性绑定器。这是一个很好的练习,基本上与选项2相同,也可能更少的代码。
// call it in your constructor
bindStuff(this, ['register', 'registerRoutes', 'etc'])
// define it somewhere as
function bindStuff (context, props) {
props.forEach(prop => {
context[prop] = context[prop].bind(context);
})
}
如果您确实想创建React组件,则可以结合使用箭头功能和属性初始化程序来执行以下操作
class OAuthComponent extends React.Component {
whateverMethodYouWant = (event) => {
this.setState({somePropertyYouCareAbout: true}) // this is bound
}
anotherMethod = () => {
this.whateverMethodYouWant() // this is bound
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句