我正在尝试在codecademy.com上学习JavaScript bij,但我似乎无法理解'this'关键字。另外,我需要更改矩形的属性宽度和高度。这是开始:
var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
// here is our method to set the height
rectangle.setHeight = function (newHeight) {
this.height = newHeight;
};
// help by finishing this method
rectangle.setWidth =
// here change the width to 8 and height to 6 using our new methods
目前我有:
var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
rectangle.setHeight = function (newHeight) {
this.height = newHeight;
};
rectangle.setWidth = function (newWidth) {
this.width = newWidth;
};
rectangle.setWidth = setWidth;
rectangle.setHeight = setHeight;
rectangle.setWidth(8);
rectangle.setHeight(6);
我做错了什么?此外,错误消息告诉我,我没有定义setWidth ...
请解释'这个'。
答案 0 :(得分:2)
这部分是正确的:
rectangle.setHeight = function (newHeight) {
// `this` here is not set yet when declaring functions
// it will be set when the function will be executed
this.height = newHeight;
};
rectangle.setWidth = function (newWidth) {
this.width = newWidth;
};
然后去做,你正在尝试做的只需要这样做:
// since these two methods are going to be called as methods of `rectangle` object
// `this` inside these functions will be set to reference `rectangle` object
rectangle.setWidth(8);
rectangle.setHeight(6);
然而,脚本没有达到上面的代码,因为这部分
rectangle.setWidth = setWidth;
rectangle.setHeight = setHeight;
会导致问题,因为setWidth
和setHeight
是对不存在的变量的引用,因此您会收到Uncaught ReferenceError: setWidth is not defined(…)
错误。而这部分实际上并不需要,所以只需删除它就可以正常工作。
JavaScript中this
上有大量资源。从MDN开始。