用JavaScript声明属性的最佳方法是什么?
如果在声明变量时使用JavaScript构建函数类型类,那么使用用JavaScript声明属性的最佳方法是什么?,javascript,Javascript,如果在声明变量时使用JavaScript构建函数类型类,那么使用 var this.variableName = variableName var this.x = x 还是像这样做更好 this.x 我尝试使用var,但它在googledebuger中出现了一个错误。为什么会出现这种情况,或者属性与函数对象中设置的变量不同 代码: 当一个对象被声明时,它已经被声明了,所以这样做不仅是非法的,而且是多余的 // DON'T DO THIS!!! var this.a = 'a'
var this.variableName = variableName
var this.x = x
还是像这样做更好
this.x
我尝试使用var,但它在googledebuger中出现了一个错误。为什么会出现这种情况,或者属性与函数对象中设置的变量不同
代码:
当一个对象被声明时,它已经被声明了,所以这样做不仅是非法的,而且是多余的
// DON'T DO THIS!!!
var this.a = 'a'; // NO!!!!!!!!!
相反,只需声明您的对象,然后向该对象追加内容,因为它已经初始化
var obj = {};
obj.a = 'a';
obj.b = 'b';
在对象中声明函数时可能会遇到的问题是范围问题以及在Javascript中如何工作
为此,您有两种选择:
声明一个可以在函数中使用的变量:
function Circle(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
// I've added the drawing code to the actual circle
// they can draw themselves.
var that = this;
this.draw = function(context){
// this refers to the global object (window)
// that refers to your Circle Object
context.beginPath();
context.arc(that.x, that.y, that.r, 0, Math.PI*2, true);
context.closePath();
context.fill();
}
}
如果使用的是ECMAScript 5支持的浏览器而不是IE8,则可以将函数绑定到圆对象
如果您想支持IE8并使用.bind,那么只需使用下划线.js并使用u.bind函数即可
function Circle(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
// I've added the drawing code to the actual circle
// they can draw themselves.
this.draw = _.bind(function(context){
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
context.closePath();
context.fill();
}, this);
}
因为var this.x=x是一个非法的语句…这个.x除了访问一个未定义的属性之外什么都不做,它不是一个声明!
function Circle(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
// I've added the drawing code to the actual circle
// they can draw themselves.
this.draw = function(context){
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
context.closePath();
context.fill();
}.bind(this);
}
function Circle(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
// I've added the drawing code to the actual circle
// they can draw themselves.
this.draw = _.bind(function(context){
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
context.closePath();
context.fill();
}, this);
}