|
|
|
|
|
by jeswin
4440 days ago
|
|
JS has some issues. But the examples in your articles mostly mean that you need to spend more time understanding the language. It seems as if you were expecting it to behave like C#. myRide = new Car("BMW");
letsDrive = myRide.drive;
letsDrive(); // alerts "You are driving a undefined"
The 'this' pointer refers to the object on which you wrote the 'dot' to invoke the function. If you wrote a.b(), then inside b() 'this' will be 'a'. In your example, you used a function pointer directly without the 'dot' and got undefined. That is not a bug or a "mine", that's how JS works.From the last article (why CoffeeScript isn't the answer) in the series: eat food for food in foods when food isn't 'chocolate'
> The declaration of what food is occurs in the middle of the line and doesn’t even look like a variable declaration. That code could easily be worse if "unless eat is undefined" was added to the end, making the whole line conditional.You'd probably have issues with Python too for it's comprehensions. You should see beyond elementary syntax if you want to make arguments about languages. These details aren't even a preference; you get used to it in no time. Summary for people jumping into JS from other languages, buy some good books because JS is somewhat different. Also, the "minefield" isn't that big a deal in practice. |
|
I completely agree. The vast majority of complaints about JS have to do with not knowing what the language is designed to do. I previously cursed JS until I spent the time to read/reread enough JS books to know what it should do. If I get unexpected behavior now, I know it's an error in my code, or I don't understand what should happen (thus time for me to read and learn).
As you pointed out, the examples yield the expected behavior.
myRide.drive();
// outputs 'BMW' b/c `this` is pointing to the instance
letsDrive = myRide.drive;
letsDrive();
// model should be undefined b/c myRide.drive is a function that is assigned to the letsDrive variable. Thus, `this` points to letsDrive, which of course does not have a `model` property.
To get letsDrive() to output a value other than undefined, we can simply create a `model` property and assign it a value.
letsDrive.model = 'Mercedes';
letsDrive();
// outputs 'Mercedes' b/c letsDrive now has a model property.
Lastly, the `delayed` method returns an anonymous function which in turn returns this.model. As JavaScript has function scope, the `this` inside the anonymous function points to the anonymous function itself. As the anonymous function does not have an attribute named `model`, undefined is returned (as expected).