DEV Community

Ashish Prajapati
Ashish Prajapati

Posted on

Day 10 of #100DaysOfCode | 1-04-2024

What I learned?

I learned the following topics:

  • JavaScript Concepts -
  1. Getters and setters
  2. Lexical Scoping and Closures

Code snippet/Screenshots/notes

JavaScript

  • getters and setters
class User {
    constructor(email, password) {
        this.email = email
        this.password = password
    }

    get email() {
        return `${this._email}`
    }

    set email(value) {
        this._email = value
    }

    get password() {
        return `${this._password}ashish`
    }

    set password(value) {
        this._password = value
    }
}

const Ashish = new User("user@yahoo.com", "password123")
console.log(Ashish.password)
console.log(Ashish.email)
Enter fullscreen mode Exit fullscreen mode
  • Object getter and setter
const User = {
    _email: "user1@gmail.com",
    _password: "password123",

    get email() {
        return this._email
    },

    set email(value) {
        this._email = value
    }
}

console.log(User._password) //Output: password123
console.log(User.email)  //Output: user1@gmail.com
Enter fullscreen mode Exit fullscreen mode

Lexical Scoping

function any() {
  let username = "user1";

  function innerFunction1() {
    let password = "pwd";
    console.log(username); //output: user1
  }

  function innerFunction2() {
    console.log(password); //output: password is not defined
  }

  innerFunction1();
  innerFunction2();
}
any();
// console.log(username) //output: username is not defined
/* child-to-child sharing is not possible  */
/* child have access to parent's properties */
/* parents don't have access to child properties */
Enter fullscreen mode Exit fullscreen mode

Closure

function handleClick(value) {

        /*return the whole lexical scope including inner function and outer function*/
        return function () {
            document.body.style.backgroundColor = `${value}`
        }
    }

    document.getElementById('black').onclick = handleClick('black')
    document.getElementById('blue').onclick = handleClick('blue')
Enter fullscreen mode Exit fullscreen mode

Top comments (0)