opticon
opticon

Reputation: 3594

JavaScript Objects and Scope

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!

Upvotes: 0

Views: 52

Answers (1)

jrsala
jrsala

Reputation: 1967

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.

Upvotes: 2

Related Questions