javascript普通对象:这个属性发生了什么?

时间:2016-10-18 03:11:57

标签: javascript html5 object

查看myGameArea对象;我知道画布是属性。但是当我调用start()方法时会发生什么?该属性现在似乎有属性,宽度和高度。所以canvas属性丢失了吗?是一个对象?有人可以解释一下吗?感谢

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    }
}

1 个答案:

答案 0 :(得分:1)

对象为myGameAreacanvas是其属性。

canvas属性不会丢失。它就在那里,可以在this.canvas内使用start()进行访问,正如您所做的那样。 canvas属性现在还拥有自己的属性,widthheight

您可以在此示例中查看console.log输出以验证:

https://jsfiddle.net/dfq4Lnho/

为了在不使用start的情况下执行此操作:

https://jsfiddle.net/dfq4Lnho/1/

var myGameArea = function() {
    this.canvas = document.createElement("canvas");
    this.canvas.width = 480;
    this.canvas.height = 270;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}

myGameArea.prototype.somethingElse = function() {
    console.log('this is a method of myGameArea');
    console.log(this.canvas); // access this.canvas here too!
}

var tmp = new myGameArea();
console.log(tmp.canvas);
tmp.somethingElse();