我有一个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");
}
}