0

I am looking for the best way to deal with this case of double context switching.

function myObject() {
    this.data = {};
}

myObject.prototype.each = function(func) {
    if (func) {
        for (var key in this.data) {
            func(key);
        }
    }
}

function myObject2() {
    this.data = {};
}

myObject2.prototype.someFunc = function(o) {
    // o = myObject
    o.each.call(this, function(key) {
        this.data[key] *= o.data[key];
    });
}

In myObject2.someFunc I use call to change the context so I can access myObject2's data. However, because of this, in myObject's each method, this now refers to myObject2. If I don't use call then I cannot access the data in myObject2.

I thought about using apply and then passing the original object as an argument and passing it back but I am looking for a more elegant solution that does not require me to change the original defition of myObject.each.

Thanks!

1
  • This code doesn't really work, right? The "each" function should be written with func.call(this, key); otherwise this in the callback from "someFunc" won't work. Commented Aug 23, 2012 at 17:44

1 Answer 1

1

That looks like it should be a generic function:

function each( obj, func, ctx ) {

    if( func ) {
        for ( var key in obj ) {
            func.call( ctx || null, key, obj[key] );
        }
    }

}

myObject2.prototype.someFunc = function(o) {
    each( o.data, function( key, value ) {
        this.data[key] = value;
    }, this );
};
Sign up to request clarification or add additional context in comments.

1 Comment

So, simple. Guess I was thinking about this too hard. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.