简体   繁体   中英

Codecademy Javascript 'this' and solution

I'm trying to learn JavaScript bij following a course at codecademy.com but I can't seem to understand the 'this' keyword. Also I need to change the properties width and height of a rectangle. This is the start:

    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

Currently I have got:

    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);

What did I do wrong? Also the Error message is telling me that I didn't define setWidth...

Please explain 'this' too.

This part is correct:

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;
};

Then to do, what you're trying to do you just need to do this:

// 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);

However, the script doesn't get to the code above, because this part

rectangle.setWidth = setWidth;
rectangle.setHeight = setHeight;

causes problems, since setWidth and setHeight are references to not existing variables and so you'll get Uncaught ReferenceError: setWidth is not defined(…) error. And this part is actually not needed, so simply remove it and it should work OK.

There's a wealth of resources on this in JavaScript. Start with MDN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM