User Tools

Site Tools


java-script:function-context

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:function-context [2023/08/09 14:07] odeftajava-script:function-context [2023/08/09 14:52] (current) odefta
Line 170: Line 170:
  
 <note important> <note important>
-Unlike normal (or named functions), the arrow functions does not have their own context, they're enclosed in the surrounding context. \\ +Unlike normal (or named functions), the arrow functions does not have their own context, they're enclosed in the surrounding context. \\ \\ 
  
 In regular functions, the value of this is determined by how the function is called, while **in arrow functions**, **this** is lexically bound, meaning it **retains the value of this from the surrounding code where the arrow function was defined**. In regular functions, the value of this is determined by how the function is called, while **in arrow functions**, **this** is lexically bound, meaning it **retains the value of this from the surrounding code where the arrow function was defined**.
 </note> </note>
 +
 +Example:
 +<code javascript ArrowFunctionContext.html>
 +<!DOCTYPE html>
 +<html lang="en">
 +<head>
 +    <meta charset="UTF-8">
 +    <title>Arrow Functions Context</title>
 +</head>
 +<body>
 +<div id="text1"> <br /> </div>
 +<div id="text2"></div>
 +<script>
 +    let person = {
 +        name: 'Preston',
 +        sayHello: () => {
 +            return `Hello - ${this.name}`;
 +        }
 +    };
 +
 +    document.getElementById('text1').innerHTML = person.sayHello(); // Hello - 
 +
 +    person = {
 +        name: 'Preston',
 +        sayHello: function() {
 +            return `Hello - ${this.name}`;
 +        }
 +    };
 +
 +    document.getElementById('text2').innerHTML = person.sayHello(); // Hello - Preston
 +
 +</script>
 +</body>
 +</html>
 +</code>
 +
 +<note>
 +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 "**Hello -** ".
 +</note>
 +
 +<note>
 +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(), this inside the sayHello method refers to the person object, and this.name evaluates to 'Preston'. The second div (text2) will have the content "**Hello - Preston**".
 +</note>
 +
 +==== 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's scope.
 +
 +Example:
 +<code javascript>
 +const parentObject = {
 +  parentValue: 'Hello from parent!',
 +  childFunction: function() {
 +    const self = this; // Storing parent's context
 +
 +    function namedFunction() {
 +      // Accessing parent's context through 'self'
 +      console.log(self.parentValue);
 +    }
 +
 +    namedFunction();
 +  }
 +};
 +
 +parentObject.childFunction(); // Outputs: Hello from parent!
 +</code>
 +
 +==== 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't have their own this** context; they inherit it from the enclosing function. This means you don't need to store the parent's context in a separate variable. \\ 
 +Same example with arrow function:
 +
 +<code javascript>
 +const parentObject = {
 +  parentValue: 'Hello from parent!',
 +  childFunction: function() {
 +    const arrowFunction = () => {
 +      // Accessing parent's context through 'this' directly
 +      console.log(this.parentValue);
 +    };
 +
 +    arrowFunction();
 +  }
 +};
 +
 +parentObject.childFunction(); // Outputs: Hello from parent!
 +</code>
 +
 +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.1691579242.txt.gz · Last modified: 2023/08/09 14:07 by odefta