JavaScript对象范围-在对象方法中使用对象变量

JavaScript Object Scope - using object variables within object methods

本文关键字:对象 变量 范围 JavaScript 方法      更新时间:2023-09-26

我正在努力理解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"answers"y"不在"this"范围内。因此,我没有使用它,而是明确地引用对象:"pattern1.x"answers"pattern1.y"。但似乎应该有更好的方法来做到这一点。

与其说我在这里寻找一个"解决方案",不如说我在寻找一个解释。谢谢

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