0

The code below passes a string to validate and function to be called if validation succeeds. In the end we reach to callback, which is object function but if fails to recognize itself as such. How to overcome the situation?

     function A(arg) {
      this.b = arg
      this.validate = function(name, cb) {
       textarea1.textContent += ("in validate, b = " + this.b + ", f = " + this.f) + "\n" 
       return cb(name)
      }
      this.f = function(name) {
       textarea1.textContent += ("in f, b = " + this.b)  + '\n'
      }
     }
     var a = new A(1)
     a.validate("name", a.f)
<textarea id="textarea1" cols=100 rows=5></textarea>

2 Answers2

0

Try the following:

return cb.call(this, name);

The method .call passes the reference of the instance to the callback so that this refers to a as expected.

JCOC611
  • 19,111
  • 14
  • 69
  • 90
  • That's working. But why is `this` needed? Is it because the callback method is inside of the same object? I've tested your code [here](http://jsfiddle.net/awolf2904/8mjxb5of/). – AWolf Jan 29 '15 at 23:36
  • @AWolf it is needed because the reference to the instance is somehow overwritten when you use `cb()`. That's the best I got. – JCOC611 Jan 29 '15 at 23:40
  • OK, thanks, not sure why the reference is lost but if I add the callback to the object A it will also work like this: `this.cb = cb; return this.cb(name);`. – AWolf Jan 29 '15 at 23:47
  • @AWolf You might not want to do that because, if you have more than one function with a callback, you might end up overwriting it. – JCOC611 Jan 29 '15 at 23:53
  • @AWolf I agree. This works but limits callback to validate enclosing object. It must be a right of user/caller to decide the parent object of the function. The ideal answer is [provided by adeneo](http://stackoverflow.com/questions/28226581/passing-object-function-as-callback-in-javascript?noredirect=1#comment44816457_28226581) in the comments. `Meta`: every time I see that formal criteria (short answer is not answer, make it a comment) is totally corrupt and primitive. That is mindset of idiots. –  Jan 30 '15 at 09:06
0

Meantime, I was puzzled by a.f.bind(a) javascript style, which I often observed in the libs, looking for the reason to use extra bind call instead of plain this.func. Adeneo obviates both confusions. That is, my example demonstrates that plain func sooner or later looses the object that it belongs to. Binding attaches the object more strongly.

Community
  • 1
  • 1