In JavaScript, this is a special keyword that points to the context object of the currently executing code: Function context: this points to the global object window. Method context: this points to the object on which the method is called. Constructor context: this points to the new object being created. Event listener context: this points to the element that triggered the event. Arrow function context: this inherits this from the parent scope.
this
in JavaScript
In JavaScript, this
is a special keyword that points to the context object of the currently executing code. Its value varies depending on the context because it can refer to a function, method, or object.
Function context
In a function context, this
always points to the global object, that is, the window
object. Therefore, when accessing this
within a function, global variables and functions can be accessed.
<code class="js">function sayHello() { console.log(this); // 输出: Window {...} }</code>
Method context
In a method context, this
always points to the object on which the method is called. This allows methods to access the object's properties and methods.
<code class="js">const person = { name: "John", sayName: function () { console.log(this.name); // 输出: John }, };</code>
Constructor context
The constructor is a function used to create and initialize objects. In constructor context, this
points to the new object being created.
<code class="js">function Person(name) { this.name = name; } const person1 = new Person("John"); console.log(person1.name); // 输出: John</code>
Other contexts
In addition to these primary contexts, this
can also be used as:
this
points to the element that triggered the event. this
in an arrow function inherits this
in its parent scope. Notes
this
does not point to the global object. If you want to access global objects, you need to use the window
object. bind()
, call()
and apply()
methods were introduced in ES6 for explicitly setting or changing ## The value of #this.
The above is the detailed content of The role of this in js. For more information, please follow other related articles on the PHP Chinese website!