I'm trying to pass to the request variable.

function custFunc() {} custFunc.prototype.one = function(options) { var this.requestCustom = request.defaults({ timeout: options.timeout || defaultTimeout }); }); 

but when you try to call a function, an error occurs from another

 custFunc.prototype.two = function(options) { this.requestCustom.get(/****/); }); 

produces: TypeError: Cannot read property 'get' of undefined

At the same time, the request through the request works normally, what am I doing wrong?

  • It is not clear where request comes from. And why the requestWrapper property should appear - vp_arth
  • extra var before initializing the requestCustom property - vp_arth

1 answer 1

You have an extra var before initializing the requestCustom property

 function custFunc() {} custFunc.prototype.one = function(options) { this.requestCustom = request.defaults({ timeout: options.timeout || defaultTimeout }); }); custFunc.prototype.two = function(options) { this.requestCustom.get(/****/); }); 

In addition, you need to understand that before using the two method, you must always call one ;

  var f = new custFunc(); f.one({}); f.two({}); 

Now, if request.defaults returns an object with a get method, everything should work.


Perhaps you can use the LazyLoad pattern:

 custFunc.prototype.two = function(options) { if (!this.requestCustom) { this.one(options); } this.requestCustom.get(/****/); }); 

@PavelMayorov suggestion:

 function custFunc(options) { this.options = options; } custFunc.prototype.one = function() { this.requestCustom = request.defaults({ timeout: this.options.timeout || defaultTimeout }); }); custFunc.prototype.two = function(options) { if (!this.requestCustom) { this.one(); } this.requestCustom.get(/****/); }); /// var f = new custFunc({timeout: 1e3}); f.two({id: 5}); 
  • For lazy execution, the options parameter must be passed to the constructor, not to each method. Otherwise there will be side effects. - Pavel Mayorov
  • I added this option, but I suspect there will be serious discrepancies with the author’s original task ( which we, naturally, have not seen ) - vp_arth