Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how is the 'this' keyword of javascript is different from 'this' keyword of java?

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.

like image 244
user2623213 Avatar asked Dec 23 '13 04:12

user2623213


People also ask

What is the key difference between Java and JavaScript?

Key differences between Java and JavaScript: Java is an OOP programming language while Java Script is an OOP scripting language. Java creates applications that run in a virtual machine or browser while JavaScript code is run on a browser only. Java code needs to be compiled while JavaScript code are all in text.

Is this keyword in JavaScript same as Java?

Java refers to the this keyword as the current state of an object defined within a class while Javascript refers to the this keyword by how a function is called.

What is difference between this keyword and this method in Java?

this keyword is used with the objects only. this() is used with constructors only. It refers to the current object. It refers to the constructor of the same class whose parameters matches with the parameters passed to this(parameters).

What is the this keyword in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.


1 Answers

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.

like image 158
Keerthivasan Avatar answered Oct 12 '22 01:10

Keerthivasan