我收到此错误:
无法读取' css'未定义
并且不知道如何解决它!
以下是代码:
//constructor for Car objects
var Car = function(x, y){
this.x = x;
this.y = y;
};
//adding the draw method to Car objects
Car.prototype.draw = function(){
//obtaining the image that the car will have
var carHtml = '<img src = "http://nostarch.com/images/car.png">';
// attaching the chosen image file to the current object being drawn
this.carElement = $(carHtml);
//giving the image of the Car object its (x, y) position on the plane using css
this.carElement.css({
position: "absolute",
left: this.x,
top: this.y
});
//attaching the image associated with the Car object to the body of the html document (the web page)
$("body").append(this.carElement);
};
//adding the moveRight method to Car objects
Car.prototype.moveRight = function(){
this.x = this.x + 50;
this.carElement.css({
left: this.x,
top: this.y
});
};
var tdi = new Car(100, 200); //creating a new instance of the Car class
tdi.draw(); //invoking the draw method on an object so it appears on the screen
var move = tdi.moveRight;
var run = setInterval(move, 30);
有任何帮助吗?在这里严重缺乏理解......
答案 0 :(得分:3)
此问题是原因,this
未引用Car
函数内的setInterval
实例。
要解决此问题,您可以使用bind
。
var run = setInterval(move.bind(tdi), 30);
或没有其他参考
var run = setInterval(tdi.moveRight.bind(tdi), 30);
此外,由于javascrip中this
上下文的行为,将this
上下文缓存在使用prototype定义的约束器和方法中是一种很好的做法。它可以防止一些问题。
例如:
Car.prototype.draw = function() {
var self_ = this;
//obtaining the image that the car will have
var carHtml = '<img src = "http://nostarch.com/images/car.png">';
// attaching the chosen image file to the current object being drawn
self_.carElement = $(carHtml);
//giving the image of the Car object its (x, y) position on the plane using css
self_.carElement.css({
position: "absolute",
left: self_.x,
top: self_.y
});
与其他语言相比,函数的此关键字在JavaScript中的行为略有不同。它在严格模式和非严格模式之间也有一些区别。
有关在javascript here中了解此背景的更多信息。
答案 1 :(得分:0)
JavaScript中“this”关键字的行为与面向对象语言不同。
你可以使用.bind()来解决它,就像建议的另一个答案一样。但是除非你理解“这个”的行为,否则你将继续讨论这个领域的问题。
简而言之:
这是一篇很好的文章:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
理解“this”,“prototype”和“closure”对编写优秀的JavaScript代码至关重要。