YouTip LogoYouTip

Js This

# JavaScript this Keyword In object-oriented languages, `this` represents a reference to the current object. However, in JavaScript, `this` is not fixed; it changes according to the execution context. * In a method, `this` refers to the object that owns the method. * If used alone, `this` refers to the global object. * In a function, `this` refers to the global object. * In a function, in strict mode, `this` is `undefined`. * In an event, `this` refers to the element that received the event. * Methods like `call()` and `apply()` can refer `this` to any object. ## Example ```javascript var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; [Try it Yourself Β»](#) * * * ## this in a Method In an object method, `this` refers to the object that "owns" the method. In the example above, `this` represents the `person` object. The `fullName` method belongs to the `person` object. ## Example ```javascript fullName : function() { return this.firstName + " " + this.lastName; } [Try it Yourself Β»](#) * * * ## this Alone When used alone, `this` refers to the global (Global) object. In a browser, the global object is `window`: ## Example ```javascript var x = this; [Try it Yourself Β»](#) In strict mode, if used alone, `this` also refers to the global (Global) object. ## Example ```javascript "use strict"; var x = this; [Try it Yourself Β»](#) * * * ## this in a Function (Default) In a function, the owner of the function is the default binding for `this`. In a browser, the global object is `window`: ## Example ```javascript function myFunction() { return this; } [Try it Yourself Β»](#) * * * ## this in a Function (Strict Mode) In strict mode, functions are not bound to `this`, so `this` is `undefined`. ## Example ```javascript "use strict"; function myFunction() { return this; } [Try it Yourself Β»](#) * * * ## this in Event Handlers In HTML event handlers, `this` refers to the HTML element that received the event: ## Example [Try it Yourself Β»](#) * * * ## Object Method Binding In the following example, `this` is the `person` object, because `person` owns the `fullName` function. ## Example ```javascript var person = { firstName : "John", lastName : "Doe", id : 5566, myFunction : function() { return this; } }; [Try it Yourself Β»](#) ## Example ```javascript var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } };
← Ts InstallProp Htmlcollection Length β†’