2015-04-06 59 views
-1

我想知道下面哪些是最好的实践?定义this.property或objectName.property的JavaScript JSON对象?

我应该使用这条语句,像这样:

var object = { 
    x: 20, 
    y: 10, 
    width: this.x, 
    height: this.y, 
    render: function() { //renders object on canvas 
    ctx.fillRect(this.x, this.y, this.width, this.height); 
    } 
}; 

或者我应该使用对象的名称,像这样:

var object = { 
    x: 20, 
    y: 10, 
    width: object.x, 
    height: object.y, 
    render: function() { //renders object on canvas 
    ctx.fillRect(object.x, object.y, object.width, object.height); 
    } 
}; 

非常感谢提前!

+0

一般要使用'this',但是这取决于该函数的调用,而不是它是如何写的。 – adeneo

+0

你什么时候使用对象名称? – Bram44444

+0

http://stackoverflow.com/q/3127429/497418 – zzzzBov

回答

-1

使用第一个,因为它是更清晰了很多其他开发商马上你指的是蝙蝠。

已取得了您尝试,所以通过使用它,你都清楚地传达你的意图,而不是混淆他们的东西。

+0

考虑到答案取决于如何调用'render',这个答案是有误导性的。如果将'render'作为回调函数传递,则需要绑定上下文或使用第二种形式。 – zzzzBov

+0

它不作为回调使用,所以“this”会很好,我想。 – Bram44444

0

这两种方案不会为你工作。

var object = { 
    x: 20, 
    y: 10, 
    width: this.x, 
    height: this.y, 
    render: function() { //renders object on canvas 
    ctx.fillRect(this.x, this.y, this.width, this.height); 
    } 
}; 

在上面的场景中width:this.x,height:this.y不起作用。因为这个关键字的对象只能在渲染函数中使用。对于写入外部渲染函数的这是窗口对象。

var object = { 
    x: 20, 
    y: 10, 
    width: object.x, 
    height: object.y, 
    render: function() { //renders object on canvas 
    ctx.fillRect(object.x, object.y, object.width, object.height); 
    } 
}; 

在第二种情况下宽度:object.x,高度:object.y不会工作,因为你正在尝试使用对象变量在其定义的中间。渲染功能内不会有任何问题。