java-script:function-context
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
java-script:function-context [2023/08/09 13:13] – ↷ Page name changed from java-script:this-function-context to java-script:function-context odefta | java-script:function-context [2023/08/09 14:52] (current) – odefta | ||
---|---|---|---|
Line 1: | Line 1: | ||
====== Java Script Function Context ====== | ====== Java Script Function Context ====== | ||
+ | |||
+ | ===== This ===== | ||
**this** keyword relates to the context on which it is run. \\ | **this** keyword relates to the context on which it is run. \\ | ||
Line 47: | Line 49: | ||
</ | </ | ||
</ | </ | ||
+ | |||
+ | ===== New ===== | ||
+ | |||
+ | The **new** operator in JavaScript is used to create a new instance of an object that's based on a constructor function. When a function is called with the new operator, the **context of this inside the function is set to the newly created object**. \\ | ||
+ | Example: | ||
+ | <code javascript> | ||
+ | function Person(name, | ||
+ | this.name = name; | ||
+ | this.age = age; | ||
+ | this.sayHello = function() { | ||
+ | console.log(' | ||
+ | }; | ||
+ | } | ||
+ | |||
+ | const alice = new Person(' | ||
+ | const bob = new Person(' | ||
+ | |||
+ | alice.sayHello(); | ||
+ | bob.sayHello(); | ||
+ | |||
+ | </ | ||
+ | |||
+ | When **new Person(' | ||
+ | The result is two distinct objects alice and bob, each with their own properties and methods. When the sayHello method is called on one of these objects, the context of this inside the method is set to the object on which the method was called. | ||
+ | <note tip> | ||
+ | Using the **new** operator in this way allows you to create reusable constructor functions that can create objects with similar properties and methods, but with different values for those properties. It's a powerful feature that enables object-oriented programming patterns in JavaScript. | ||
+ | </ | ||
+ | |||
+ | ===== Call, Apply, Bind ===== | ||
+ | |||
+ | The **call**, **apply**, and **bind** methods in JavaScript are used to control the value of **this** inside a function. \\ They allow you to call a function with a specific context for this, and also pass arguments to the function. \\ | ||
+ | By using call, apply, or bind, you can ensure that the function behaves correctly regardless of how it's called. \\ | ||
+ | We'll use this code to show how these functions are called: | ||
+ | <code javascript> | ||
+ | function sayHello(greeting, | ||
+ | console.log(greeting, | ||
+ | } | ||
+ | |||
+ | const person = { | ||
+ | name: ' | ||
+ | age: 30 | ||
+ | }; | ||
+ | |||
+ | const spouse = { | ||
+ | name: ' | ||
+ | age: 32 | ||
+ | }; | ||
+ | </ | ||
+ | |||
+ | ==== Call ==== | ||
+ | |||
+ | The **call** method allows you to pass **individual arguments after specifying the value for this**. | ||
+ | |||
+ | <code javascript> | ||
+ | sayHello.call(person, | ||
+ | sayHello.call(spouse, | ||
+ | </ | ||
+ | |||
+ | ==== Apply ==== | ||
+ | |||
+ | The **apply** method is similar to call, but it **takes an array-like object for the arguments, instead of individual arguments.** | ||
+ | |||
+ | <code javascript> | ||
+ | sayHello.apply(person, | ||
+ | sayHello.apply(spouse, | ||
+ | </ | ||
+ | |||
+ | ==== Bind ==== | ||
+ | |||
+ | The **bind** method allows you to **create a new function with a bound context for this, and you can then call that function with any arguments you like.** | ||
+ | |||
+ | <code javascript> | ||
+ | const sayHelloToPerson = sayHello.bind(person); | ||
+ | const sayHelloToSpouse = sayHello.bind(spouse); | ||
+ | |||
+ | sayHelloToPerson(' | ||
+ | sayHelloToSpouse(' | ||
+ | </ | ||
+ | |||
+ | <note tip> | ||
+ | These methods are particularly useful when working with functions that rely on a specific context for this, such as event handlers or methods that need to be reused with different objects. | ||
+ | |||
+ | Imagine you have two buttons on a web page, each representing different users, and you want to greet the user with their name when the button is clicked. \\ | ||
+ | HTML: | ||
+ | <code html> | ||
+ | <button id=" | ||
+ | <button id=" | ||
+ | </ | ||
+ | |||
+ | JAVA SCRIPT: | ||
+ | <code javascript> | ||
+ | function greetUser(greeting) { | ||
+ | alert(greeting + ' ' + this.name + ' | ||
+ | } | ||
+ | |||
+ | const userAlice = { | ||
+ | name: ' | ||
+ | }; | ||
+ | |||
+ | const userBob = { | ||
+ | name: ' | ||
+ | }; | ||
+ | |||
+ | // Using bind to create functions with the correct context for this | ||
+ | const greetAlice = greetUser.bind(userAlice, | ||
+ | const greetBob = greetUser.bind(userBob, | ||
+ | |||
+ | // Adding event listeners | ||
+ | document.getElementById(' | ||
+ | document.getElementById(' | ||
+ | |||
+ | </ | ||
+ | |||
+ | Here, we're using the **bind** method to create two new functions, **greetAlice** and **greetBob**, | ||
+ | This example illustrates how the **bind** method can be used to create reusable functions with different contexts for **this**, allowing you to write more modular and maintainable code. \\ | ||
+ | Similar principles apply when using **call** and **apply** to control the context of **this** in other situations. | ||
+ | </ | ||
+ | |||
+ | ===== Arrow Functions Context ===== | ||
+ | |||
+ | <note important> | ||
+ | Unlike normal (or named functions), the arrow functions does not have their own context, they' | ||
+ | |||
+ | In regular functions, the value of this is determined by how the function is called, while **in arrow functions**, | ||
+ | </ | ||
+ | |||
+ | Example: | ||
+ | <code javascript ArrowFunctionContext.html> | ||
+ | < | ||
+ | <html lang=" | ||
+ | < | ||
+ | <meta charset=" | ||
+ | < | ||
+ | </ | ||
+ | < | ||
+ | <div id=" | ||
+ | <div id=" | ||
+ | < | ||
+ | let person = { | ||
+ | name: ' | ||
+ | sayHello: () => { | ||
+ | return `Hello - ${this.name}`; | ||
+ | } | ||
+ | }; | ||
+ | |||
+ | document.getElementById(' | ||
+ | |||
+ | person = { | ||
+ | name: ' | ||
+ | sayHello: function() { | ||
+ | return `Hello - ${this.name}`; | ||
+ | } | ||
+ | }; | ||
+ | |||
+ | document.getElementById(' | ||
+ | |||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | |||
+ | < | ||
+ | In the first part, we have defined sayHello as an arrow function. **Arrow functions don't have their own this**, so the this keyword inside the arrow function refers to the lexical context, which in the case of a script running in a browser would be the global window object. Since window.name is undefined, the first div (text1) will have the content " | ||
+ | </ | ||
+ | |||
+ | < | ||
+ | In the second example, we have defined sayHello as a regular function. **Regular functions have their own this** context, which refers to the object they are called on. So, when we call person.sayHello(), | ||
+ | </ | ||
+ | |||
+ | ==== How to access the context of a parent object inside a nested (child) named function ==== | ||
+ | |||
+ | Here we'll need to assign the context of the parent object to a variable that the nested function can access. \\ This is commonly done by **assigning this to a variable, often named self or that**, in the parent object' | ||
+ | |||
+ | Example: | ||
+ | <code javascript> | ||
+ | const parentObject = { | ||
+ | parentValue: | ||
+ | childFunction: | ||
+ | const self = this; // Storing parent' | ||
+ | |||
+ | function namedFunction() { | ||
+ | // Accessing parent' | ||
+ | console.log(self.parentValue); | ||
+ | } | ||
+ | |||
+ | namedFunction(); | ||
+ | } | ||
+ | }; | ||
+ | |||
+ | parentObject.childFunction(); | ||
+ | </ | ||
+ | |||
+ | ==== How to access the context of a parent object inside a nested (child) arrow function ==== | ||
+ | |||
+ | Using an **arrow function** can simplify the code because arrow functions **don' | ||
+ | Same example with arrow function: | ||
+ | |||
+ | <code javascript> | ||
+ | const parentObject = { | ||
+ | parentValue: | ||
+ | childFunction: | ||
+ | const arrowFunction = () => { | ||
+ | // Accessing parent' | ||
+ | console.log(this.parentValue); | ||
+ | }; | ||
+ | |||
+ | arrowFunction(); | ||
+ | } | ||
+ | }; | ||
+ | |||
+ | parentObject.childFunction(); | ||
+ | </ | ||
+ | |||
+ | By using an arrow function for the inner function, we automatically capture the value of this from the enclosing childFunction method. This allows the inner function to access the properties and methods of the parentObject without needing to assign this to a separate variable. | ||
+ | \\ It's a cleaner and more concise way to write code that depends on maintaining the context of this across different levels of nested functions. | ||
+ | |||
+ | |||
+ | |||
+ | |||
java-script/function-context.1691576020.txt.gz · Last modified: 2023/08/09 13:13 by odefta