JavaScript对象和范围

时间:2014-11-21 19:45:15

标签: javascript

我有一些看起来像这样的JavaScript:

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;
});

另一个文件中的对象如下所示:

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

        callback();
    }

    module.exports = OtherObject;
});

我希望让OtherObject在内部发生某些事情时使用回调,并让该回调访问MyObject文件中实例化的对象。但是,每当调用moving()时,this.currentThing都是未定义的。我可能会忽视这里显而易见的事情,但我很乐意帮助你!

1 个答案:

答案 0 :(得分:2)

这是因为调用thiscallback的值movingMyObject函数的值不是{{1}}实例。

我可以告诉你如何解决你的问题,但这很难教你。相反,请阅读this然后this,而不是双关语。