简体   繁体   中英

Accessing private members in JavaScript constructor

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);
}

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:

  1. Create getFileName in the constructor, so it closes over it, or
  2. Save it as a property on the instance ( this ) and then use it from that property

Have 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+)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM