I have a Sailsjs service class I declared my functions and everything is working fine not until when I tried to access this
from within a function to call another, it was null. Doing some googling, I notice calling this
in a function would print {}
. So, if I'm right with my thought, this
in an ES6
arrow function only conforms to the function itself. But, how can I make a SailsJs
function written in ES6 Arrow Function
access the global this
itself. Below is what I tried:
Without ES6 Arrow Functions
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 Function
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");
}
}