Reputation: 1110
Say I have this
function FileHelper() {
var _path = require("path");
}
I have seen 2 ways of implementing constructor methods.
function FileHelper() {
var _path = require("path");
this.getFileName = function() {
// can reference _path here
}
}
and
function FileHelper() {
var _path = require("path");
}
FileHelper.prototype.getFileName = function () {
// cannot reference _path here
}
I'm leaning towards "attaching" the implementation of methods to the contructor's prototype, and would like to, if possible, keep any dependencies contained within the constructor itself, as opposed to declaring them as globals in the constructor's file.
with that said, is there a way to achieve the following?
function FileHelper() {
var _path = require("path");
}
FileHelper.prototype.getFileName = function (filePath) {
// _path is successfully referenced without reference error
return _path.basename(filePath);
}
Upvotes: 0
Views: 43
Reputation: 1074138
with that said, is there a way to achieve the following?
No. The _path
declared in the constructor is a local variable. It's entirely private to the constructor and goes away after the constructor terminates, since the constructor doesn't create any closures that would retain it.
If you want to keep using it, either:
getFileName
in the constructor, so it closes over it, orthis
) and then use it from that propertyHave said that: Accessing something via require
within a constructor seems like a bit of an antipattern. Since it won't change, just access it outside the constructor, for instance:
var FileHelper = (function() {
var _path = require("path");
function FileHelper() {
}
FileHelper.prototype.getFileName = function() {
// ...use _path here...
};
return FileHelper;
})();
(I've kept that at ES5-level syntax because your question seems to be avoiding using ES2015+)
Upvotes: 1