0

I have some JavaScript that looks like this:

define(function(require, exports, module) {
    // Constructor function for our ContentView class
    var OtherObject = require('OtherObject');

    function MyObject() {
        this.currentThing = null;

        setThing();
        var b = new OtherObject(moving);
    }

    function setThing() {
        this.currentThing = "A string!";
    }

    function moving() {
        console.log(this.currentThing);        
    }

    module.exports = MyObject;
});

And an object in another file that looks like this:

define(function(require, exports, module) {
    // Constructor function for our ContentView class
    function OtherObject(callback) {
        this.whatever = null;

        callback();
    }

    module.exports = OtherObject;
});

I want to let the OtherObject use a callback when something happens internally, and have that callback access an object instantiated in the MyObject file. However, whenever moving() is called, this.currentThing is undefined. I'm probably overlooking something obvious here, but I'd love some help!

1
  • this in setThing() and moving() is not a MyObject, it's window. Those functions are defined outside of the scope of MyObject. Commented Nov 21, 2014 at 19:52

1 Answer 1

2

That's because the value of this when callback is called and its value is the moving function is not the MyObject instance.

I could tell you how to fix your problem, but that would hardly teach you much. Instead, read this and then this, no pun intended.

Sign up to request clarification or add additional context in comments.

Comments

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.