nodeJS - 无法在构造函数的原型方法中达到此属性

时间:2017-11-15 21:53:40

标签: javascript node.js

我在构造函数中描述了属性,但是当我在index.js中调用Server.request方法时,它没有显示属性

console.log(this)

输出{}(空对象)

构造

function Server(){
  if(!(this instanceof Server)) return new Server()

  this.actions = { // accepted actions
    login: {
      post: [['email', 'username'], 'password']
    },
    register: {
      post: 'name,surname,password,email,haveLicence,licenceKey'.split(',')
    }
  }
}

请求功能

Server.prototype.request = (req /* express request object */)=>{
  console.log(this) // {}
  return new Promise((r,j)=>{
    let action = (req.url.match(/[a-z\-]+/i) || [])[0]

    if(!action) return r([400, 'NoAction']);

    action = this.actions[action] // Cannot read property 'register' of undefined.
...
}

1 个答案:

答案 0 :(得分:2)

这是es6箭头功能的本质。它们以不同的方式绑定this

尝试:

Server.prototype.request = function(req) {
    console.log(this) // 
    // etc.
}

简化示例:



function Server() {
  this.string = "hello"
}

Server.prototype.request = function(req) {
  return this.string
}
Server.prototype.request_arrow = (req) => {
  return this.string
}
var s = new Server()

console.log(s.request())
console.log(s.request_arrow())