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.
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.
Share Improve this question asked Dec 23, 2013 at 4:56 user2623213user2623213 2332 gold badges4 silver badges11 bronze badges 7 | Show 2 more comments3 Answers
Reset to default 9In 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.
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.
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.
this
key word in both case refer the current object. – Subhrajyoti Majumder Commented Dec 23, 2013 at 4:56this
can also refer to an element triggering an event. – user1890615 Commented Dec 23, 2013 at 4:59undefined
. – RobG Commented Dec 23, 2013 at 5:02