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.
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With