11

How is the 'this' keyword of javascript is different from 'this' keyword of java?any practical example will be appreciated.

var counter = {
  val: 0,
  increment: function () {
    this.val += 1;
  }
};
counter.increment();
console.log(counter.val); // 1
counter['increment']();
console.log(counter.val); // 2

in java:

 public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

thanks.

user2623213
  • 213
  • 2
  • 4
  • 10
  • 2
    `this` key word in both case refer the current object. – Subhrajyoti Majumder Dec 23 '13 at 04:56
  • 1
    In javascript, `this` can also refer to an element triggering an event. –  Dec 23 '13 at 04:59
  • 8
    Java is not Javascript, so I think comparison you are doing is, between apples and oranges, which doesn't make sense. – kosa Dec 23 '13 at 04:59
  • possible duplicate of [java programming language](http://stackoverflow.com/questions/3637558/java-programming-language). (I know that is a "closed" Question, but the first Answer clearly and succinctly answers this one too.) – Stephen C Dec 23 '13 at 05:01
  • In ECMAScript, *this* is set either by the call or using *bind*. It can reference **any** object and be different for each call. In addition, in strict mode, *this* can be set to **any** value by the call, including `undefined`. – RobG Dec 23 '13 at 05:02
  • @StephenC: Hardly. Rather, possible duplicate of http://stackoverflow.com/questions/3127429/javascript-this-keyword – nitro2k01 Dec 23 '13 at 05:02
  • @nitro2k01 - That Question is only about Javascript, and its Answers are only about Javascript. – Stephen C Dec 23 '13 at 05:04

3 Answers3

8

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

In Java, this refers to the current instance object on which the method is executed.

Keerthivasan
  • 12,040
  • 2
  • 26
  • 49
7

JavaScript is a bit peculiar when it comes to the keyword "this".

In JavaScript, functions are objects, and the value of "this" depends on how a function is called.

In fact, just read the linked article to understand how JavaScript treats the "this" keyword--drink plenty of coffee first.

Nostalg.io
  • 3,322
  • 1
  • 21
  • 31
2

ECMAScript defines this as a keyword that "evaluates to the value of the ThisBinding of the current execution context" (§11.1.1). The interpreter updates the ThisBinding whenever establishing an execution context.

In Java this refers to the current instance of the method on which it is used. There is a JVM, and no interpreter.

Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226