我正在尝试学习JavaScript bij遵循codecademy.com的课程,但我似乎无法理解'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);
我做错了什么?另外,错误信息告诉我,我没有定义settwidth…
请把"this"也解释一下
这部分是正确的:
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开始