Why use 'this' keyword in rectangle example?


#1



Note we have used the keyword this. this is still a placeholder, but in this scenario, this can only ever refer to rectangle because we defined setHeight to be explicitly part of rectangle by defining it as rectangle.setHeight.


Why use the keyword 'this' at all in this scenario? I thought the idea was to use this so it could apply to many objects? Not sure I get the point, or advantage of using 'this' in this scenario?

Replace this line with your code.


#2

@chipeter,

+++ this explained

Reference::

google search
== the Book ==
javascript this site:developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Have a read through
http://stackoverflow.com/questions/4354418/var-vs-this-vs-constructor-parameter-variables
and
http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/


#3

Thanks but all of those articles are way over my head. Maybe when I have learned more it will make sense. Thanks anyway!


#4

@chipeter,
Maybe if you use this piece of code
you will get an idear

// define a =global= VARIABLE
var line = 3;
var myObj = {
    //define an Object property
    line:5,
    display_outside: function() {
        console.log(line);
    },
    display_inside: function() {
        console.log(this.line);
    }
};
myObj.display_outside();
myObj.display_inside();
nice to know

You could test in labs.codecademy.com
choose Javascript
You will get a split-screen
In the left-hand-side you paste-in your code
click on the Run button.
The right-hand-side is the console

references

www.crockford.com --> for most respected guide-line in Javascript
like coding convention
www.crockford.com
http://javascript.crockford.com/code.html <== Javascript code-convention
http://javascript.crockford.com/survey.html


#5

@chipeter I just got to this exercise and wondered this (hardy har) exact thing as well!
And for the same reason as you: "In this scenario, this can only ever refer to rectangle" [and we are unlikely to rename the variable in this exercise].

I think I've generally got the concept of this... In this lesson I went with rectangle.width 'cause I'm a rebel :imp:

Seriously though, my guess'd be that it's just practice writing this in the barest possible context to like, practice it? But it'd be nice to have some kind of confirmation. In terms of an irl example that might resemble this one I did find the following:

Other than that, I imagine that (on some browsers) there may be some performance gain too, since with user.name browser has to lookup in context outside your function while using this.name sticks to current context. (stackoverflow)

In addition to the circumstances I, and, I imagine, you, were thinking of (variable name change, method applied to multiple objects, etc.).

Have you gotten any further on figuring out an answer to this in the two weeks since you've posted?

frisby