我正在尝试在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 ...

请也解释一下“这个”。

最佳答案

这部分是正确的:

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;


会导致问题,因为setWidthsetHeight是对不存在的变量的引用,因此会出现Uncaught ReferenceError: setWidth is not defined(…)错误。而且实际上不需要此部分,因此只需将其删除即可正常工作。

JavaScript中this上有大量资源。从MDN开始。

09-11 20:48