Hacker News new | ask | show | jobs
by akbar501 4441 days ago
> 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).

1 comments

Your example is wrong. You can't attach object properties to a function.

Javascript context is pretty simple. The keyword 'this' by default points at the object that the method belongs to. When you invoke this function :

myRide.drive();

the myride object owns the drive function, so any keyword 'this' inside of the drive function will be referring to the myride object.

when you do this:

letsDrive = myRide.drive;

letsdrive is now a function that belongs to the global object (window) since we did not declare an object for it. So 'this' is reffering to the window object.To get the output in your example, you would say

window.model = 'Mercedes';

And invoking letsdrive() will now return the expected result

Functions are objects, and you can attach properties to them.

  function foo() {}
  foo.bar = 7;
  console.log(foo.bar); // prints 7
I stand corrected on not being able to attach properties to a function, but what I said still holds true. The keyword this refers to the object that owns the method. The original commenter was saying that it was the method itself that was what this points at.

letsdrive = myRide.drive window.model = 'mercedes'; letsdrive.model = 'bmw';

letsdrive(); // outputs mercedes