Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript setInterval创建新对象_Javascript_Class_Prototype - Fatal编程技术网

Javascript setInterval创建新对象

Javascript setInterval创建新对象,javascript,class,prototype,Javascript,Class,Prototype,我正在用JavaScript编写一个小应用程序,我有一个类和一个原型方法 function Canvas(_canvasId, _page) { this.c = document.getElementById(_canvasId); this.ctx = this.c.getContext("2d"); this.page = _page; }; Canvas.prototype.draw = function () { console.log(this);

我正在用JavaScript编写一个小应用程序,我有一个类和一个原型方法

function Canvas(_canvasId, _page) {
    this.c = document.getElementById(_canvasId);
    this.ctx = this.c.getContext("2d");
    this.page = _page;
};

Canvas.prototype.draw = function () {
    console.log(this);

    switch (this.page) {
        case "_CitySystem":
            //this.renderCitySystem();
            break;
    }
};
然后创建一个新实例并调用draw方法:

$(document).ready(function () {
    var g = new Canvas("cCity", "_CitySystem");
    setInterval(g.draw, 1000);
});
我遇到的问题是当我这样做的时候

console.log(this);
我希望它输出画布对象属性,而不是windows对象属性:

我是怎么做的

d.draw();
如果没有setInterval,控制台输出就是我所期望的,因此在setInterval中的回调中,最终结果是一个不同的对象,我如何告诉setInterval我想要使用我传入的对象属性?

用函数{g.draw;}替换g.draw。

调用或时,你真的是在对着窗户说话

您需要传递上下文,这可以通过jQuery.proxy完成:

setInterval($.proxy(g.draw, g), 1000);

请参阅位于以下位置的文档:

g.draw.bindg也有一些冗余。