我无法理解如何在以下代码中使用'this'。我正在用Raphael.js和Jquery创建圈子。
$(function(){
function circleAttributes(x, y, r){
this.x = x;
this.y = y;
this.r = r;
this.strokeweight = 3;
console.log(x,y,r, this.x);
}
var paper = Raphael(0, 0, 1200, 600);
var circles = [];
for(var i = 0; i < 20; i++){
circles.push(new circleAttributes(Math.floor(Math.random() * 500), Math.floor(Math.random() * 500), 5));
paper.circle(circles[i].x, circles[i].y, circles[i].r);
console.log(circles);
}
});
这一切都运行正常,但如果我将this.x
更改为circleAttributes.x
,我似乎无法访问行paper.circle(circles[i].x, circles[i].y, circles[i].r);
中的x。
我写circles[i].circleAttributes.x
吗?这似乎也不起作用,但我觉得它应该能够!它应该就像说person.name
或?
我知道'this'就像代词'他'一样。迈克逃跑了,因为他很害怕。
编辑:我仍然不明白,请有人用简单的语言解释一下!
答案 0 :(得分:0)
当您调用'this'.property or 'this'.method
时,您只是引用初始化操作或功能的父对象。它可以节省您编写所有内容的时间,当您为对象名称,id或您在调用它时使用的通配符创建一个chnage时,您不必更改它之间出现的所有行。
jQuery时你有
$('#btn').click(function() {
//you can access the btn object like below
$(this).text('click me');
$(this).show();
});
答案 1 :(得分:0)
“this”不是代词(如果我们将代词视为指针)。 “this”是其使用的函数的对象实例。 circles [i] .circleAttributes.x表示您正在尝试访问circleAttributes函数中的circleAttributes.x,即您需要声明circleAttributes.circleAttributes.x以此方式访问它。