V
V
vasIvas2014-08-31 19:07:22
JavaScript
vasIvas, 2014-08-31 19:07:22

How to be, if callback'y substitute a context (an ordinary and OOP decision)?

function Two(){
  One.call(this);
}

Two.prototype = Object.create(One.prototype);
Two.prototype.constructor = Two;

Two.prototype = {
  setParams: function(num){
    this.prop = num
  },
  prop: null
}

var two = new Two();
two.setParams(1);
console.log(two.prop);

There is a module where you need to send a callback to get data about the file system.
I created an object that was supposed to process data in a method that is passed as a callback (I have a setParams method). But it turned out that the module passing parameters to the callback replaces the context with it and therefore this no longer works.
And from here I have two questions at once -
1) How to get around this?
2) How to get around this most competently (I'm sure that patterns were invented for such cases, explain in words what they are called, I'll navigate the book and then ask more questions how to apply them)?
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Petrov, 2014-08-31
@vasIvas

Can you explain this design to me?

function One(){
  // Очевидно, устанавливает this свойства и методы
}
function Two(){
  One.call(this);
}
Two.prototype = Object.create(One.prototype);
Two.prototype = {
  setParams: function (num) {
    this.prop = num;
  },
  prop: null
};

What is not clear to me:
1. Is it really necessary to write own methods in each new Two() object? Maybe it's easier to inherit from the One prototype? But then the approach to creation should be different.
2. Why did we refer to the One prototype and immediately erased this link?
If I wanted to inherit from One and add mine to Two, I would have acted differently:
function One(){}
function Two(){}
function F(options) {
  for (var i in options) {
    if (options.hasOwnProperty(i)) {
      this[i] = options[i];
    }
  }
}

One.prototype = {
  // наследуемые свойства и методы
};
F.prototype = One.prototype;
Two.prototype = new F({
  setParams: function (num) {
    this.prop = num;
  },
  prop: null
});

What about the question - show the code with the transfer of callback.

A
akarin, 2014-08-31
@akarin

>1) How to get around this?
"Bind" this to another context

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question