Josh
Josh

Reputation: 690

How to find the initial creator of an instance object in JavaScript?

Let's say I have the following code:

var Foo = (function () {

    //constructor
    var Foo = function (callbackFunction) {
        this.callbackFunction = callbackFunction;
    };

    //method
    Foo.prototype = {
        run: function () {
            if (typeof(this.callbackFunction) === 'function') {
                this.callbackFunction.call(???); //??? should be the object that created this Foo instance.
            }
        }   
    };
    return Foo;
})();

this is saved in foo.js

I also have the following code:

var Bar = (function () {

    //constructor
    var Bar = function (v1, v2) {
        this.v1 = v1;
        this.v2 = v2;
    };

    Bar.prototype.callback = function() {
        //'this' should be the instance of Bar
        console.log('value of v1 is ' + this.v1 + ' value of v2 is ' + this.v2);
    }

    Bar.prototype.callFoo = function() {
        this.foo = new Foo(this.callback);
        this.foo.run();
    }

    return Bar;
})();

var bar1 = new Bar('apple', 'orange');
bar1.callFoo();
var bar2 = new Bar('grape', 'banana');
bar2.callFoo();

again, this is saved inside bar.js

inside Foo, I have this line: this.callbackFunction.call(???);

So, in order to make this work, I have to pass the object that created the instance of Foo to the call function, but how?

Upvotes: 0

Views: 283

Answers (1)

Katana314
Katana314

Reputation: 8610

My recommendation is to use the function.bind() method.

Mozilla Developer Network:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

It might be difficult to find a way to pass Bar into Foo.callbackFunction, but if Bar passes in this.callbackFunction.bind(this), then Foo can just call this.callbackFunction() without passing arguments (or using call)

There are also some JavaScript libraries that let you do this in older browsers, since bind() is a relatively new feature. For instance, in Dojo it's called hitch().

Upvotes: 4

Related Questions