GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing javascript.info — Explain the value of "this"

  • Tutorial
  • The JavaScript language
  • Miscellaneous
  • Reference Type
back to the lesson

Explain the value of "this"

importance: 3

In the code below we intend to call obj.go() method 4 times in a row.

But calls (1) and (2) works differently from (3) and (4). Why?

let obj, method;

obj = {
  go: function() { alert(this); }
};

obj.go();               // (1) [object Object]

(obj.go)();             // (2) [object Object]

(method = obj.go)();    // (3) undefined

(obj.go || obj.stop)(); // (4) undefined

Here’s the explanations.

  1. That’s a regular object method call.

  2. The same, parentheses do not change the order of operations here, the dot is first anyway.

  3. Here we have a more complex call (expression)(). The call works as if it were split into two lines:

    f = obj.go; // calculate the expression
    f();        // call what we have

    Here f() is executed as a function, without this.

  4. The similar thing as (3), to the left of the parentheses () we have an expression.

To explain the behavior of (3) and (4) we need to recall that property accessors (dot or square brackets) return a value of the Reference Type.

Any operation on it except a method call (like assignment = or ||) turns it into an ordinary value, which does not carry the information allowing to set this.

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.