Quantcast
Viewing all articles
Browse latest Browse all 16

Codewars JavaScript Kata #2

Correct the following code:
[gist id=”420b3f151a6bb94658bb” file=”codewars_javascript_kata_02_problem.js”]

Here’s my solution:
[gist id=”420b3f151a6bb94658bb” file=”codewars_javascript_kata_02_solution.js” highlight=”7″]

Here’s my understanding of why this works. But first, a quick disclaimer. I am not a pro by any stretch of the imagination, not even an amateur. None of this is meant to be taken as spot-on, 100% perfect. I’m very much learning as I go. Instead, please consult the JavaScript Resources I have listed in the sidebar. They’re awesome.

Ok, here goes. Our goal is to point name in the greet function to the name property of the Person() object.

As it’s written originally, however, name points to a global name variable that doesn’t exist, and NOT the Person.name property.

Fortunately, by changing name to this.name, we’ve done just that, pointing to the actual name property of the Person() object.

How does this work? Well, the greet function itself is another property of the Person object.

When we invoke this.name within the lexical scope of greet, we’re referencing back to the parent object, i.e. Person, which allows us to access its other properties as well. In this case, name.

Here’s the example I used to get it working:
[gist id=”420b3f151a6bb94658bb” file=”codewars_javascript_kata_02_working_example.js”]


Viewing all articles
Browse latest Browse all 16

Trending Articles