Answer the question
In order to leave comments, you need to log in
How to hide a utility method?
Hello! How to hide a utility method? When adding ennumerable: false to the method descriptor, but in this case I cannot use it in other methods of the object, it throws the error "TypeError: this._load is not a function". Who will advise what?
"use strict"
var fs = require('fs');
function Settings(pathToJson) {
typeof pathToJson === "string" ? this.reload(pathToJson) : this.reload('./settings.json');
Object.defineProperties(this, {
_load: {enumerable: false},
settings: {enumerable: false}
});
Object.freeze(this);
}
Settings.prototype = {
reload: function(path){
this.settings = fs.readFileSync(path, 'utf-8');
this.settings = this.settings.replace(/\/\/.*/g, '');
this.settings = JSON.parse(this.settings);
},
_load: function(){
fs.writeFileSync('settings.json', JSON.stringify(this.settings, false, '\t'));
},
get include(){
return this.settings.include;
},
set include(arg){
if (arg instanceof Array) { // В том случае если передают массив
var _ = this;
arg.forEach(function(c, i){
// Если в массиве находятся не строки выкидывает ошибку!
if (!(typeof c === 'string')) throw new Error('Path not readable!');
// Если путь найден в инклудах или ексклудах путь не подключается!
if(~_.include.indexOf(c) || ~_.exclude.indexOf(c)) return;
// Создание инклуда и подключение путей
_.include = [];
_.include.push(c);
console.log('includig ' + c);
});
this._load(); // <== Здесь выскакивает ошибка
}
else if (typeof arg === 'string'){ // В том случае если передают один путь
if(~this.include.indexOf(arg) || ~_.exclude.indexOf(arg)) return;
this.include = []; // Создание инклуда и подключение путей
this.include.push(arg);
this._load(); // <== Здесь выскакивает ошибка
}
else throw new Error('Path not readable!');
},
get exclude(){
return this.settings.exclude;
}
}
Answer the question
In order to leave comments, you need to log in
Use Node.js 6, it already has classes and arrow functions. The code will become much more compact and beautiful.
Regarding service methods: if you mean private methods, then there is no special need for this. But if you still really need it, this is done through a Symbol, WeakMap or a closure. Examples can be easily googled. There is also an option with decorators https://github.com/elado/class-private-method-decorator
But for it you need to include Babel in the project.
PS If you need a clean syntax, you can use TypeScript. Example from documentation:
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; // Error: 'name' is private;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question