【问题标题】:JavaScript Object Scope - using object variables within object methodsJavaScript Object Scope - 在对象方法中使用对象变量
【发布时间】:2015-05-27 09:43:28
【问题描述】:

我正在尝试理解 JavaScript 对象语法。我有一个要绘制的画布元素,我想更改我绘制的图案。我希望它能像这样工作:

pattern1 = {
    'x':0,
    'y':0,
    'draw': function() {
        context.clearRect(0,0,w,h);
        context.save();
        context.translate(this.x, this.y);
        context.fillText('Hello', 0, 0);
        context.restore();
        this.x += 1;
        this.y += 1;
    }
};

但这不起作用。 “x”和“y”变量不在“this”范围内。因此,我没有使用它,而是明确地引用了对象:“pattern1.x”和“pattern1.y”。但似乎应该有更好的方法来做到这一点。

我并不是在这里寻找“解决方案”作为解释。谢谢。

【问题讨论】:

标签: javascript scope closures this


【解决方案1】:
pattern1 = function (){
    this.x=0;
    this.y=0;
    this.draw= function() {
        context.clearRect(0,0,w,h);
        context.save();
        context.translate(this.x, this.y);
        context.fillText('Hello', 0, 0);
        context.restore();
        this.x += 1;
        this.y += 1;
    }
};

var patObj=new pattern1 ();    // Function Calling
patObj.draw();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多