在Sailsjs es6箭头函数

时间:2017-02-12 17:09:03

标签: javascript node.js ecmascript-6 sails.js

我有一个Sailsjs服务类我声明了我的函数,一切正常,直到我尝试从函数内部访问this来调用另一个函数时,它才为空。做一些谷歌搜索,我注意在函数中调用this会打印{}。所以,如果我的想法是正确的,this箭头函数中的ES6只符合函数本身。但是,如何在SailsJs中编写ES6 Arrow Function函数来访问global this本身。以下是我的尝试:

没有ES6箭头功能

const Promise = require('bluebird');

module.exports = {

    uploadFile: function(req) {
        const self = this;
        console.log(self); <-- Prints MainLOG
        console.log(self.logData); <-- Prints "I was able to be reference"
        return new Promise((resolve, reject) => {
            req.file('images').upload({
                dirname: process.cwd() + "/.tmp/Upload"
            }, (error, files) => {
                return error ? reject(error) : resolve(files);
            });
        });
    },

    logData: () => {
        console.log("I was able to be reference");
    }
}


MainLOG: { uploadFile: [Function: wrapper],
  logData: [Function: wrapper],
  identity: 'uploadservice',
  globalId: 'UploadService',
  sails:

  |>   [a lifted Sails app on port 1510]
   \___/  For help, see: http://sailsjs.org/documentation/concepts/

   Tip: Use `sails.config` to access your app's runtime configuration.

   7 Models:
   Bla, Bla, Bla

   8 Controllers:
   Bla, Bla, Bla

   21 Hooks:
   bla, bla, bla
}

ES6功能

const Promise = require('bluebird');

module.exports = {

    uploadFile: (req) => {
        const self = this;
        console.log(self); <-- Prints {}
        console.log(self.logData); <-- Prints undefine
        return new Promise((resolve, reject) => {
            req.file('images').upload({
                dirname: process.cwd() + "/.tmp/Upload"
            }, (error, files) => {
                return error ? reject(error) : resolve(files);
            });
        });
    },

    logData: () => {
        console.log("I was able to be reference");
    }
}

0 个答案:

没有答案