JavaScript Basic - this, closure, Math.random(), DOM... | DevsDay.ru

IT-блоги JavaScript Basic - this, closure, Math.random(), DOM...

dev.to 6 декабря 2021 г.


**

arr2 = [2, 3, 4, 5]; // assigning to array
arr1 = [1, 2, 3, 4];

arr3 = arr1; // now arr3 and arr1 are referencing the same array
arr3[3] = 0;  // this change even the referenced array that's stored in arr1 (because they are getting the reference from the same thing)

arr1;
// [1, 2, 3, 0]

** Array/Object are reference type! If you assign array to new variable, it is not copying the array to the new variable but it's referencing it.

let str = 'welcome';

str;
// 'welcome'

str[0]
// 'w'

str[0] = 'v'
// 'v'

str;
// 'welcome'

string is primitive type. When you assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable.

JavaScript uses prototype-based programming, which is a type of object oriented programming. Prototypes are a way of reusing behaviors by cloning existing objects instead of doing class based inheritance. (https://en.wikipedia.org/wiki/Prototype-based_programming)

this

function aboutThis() {
    console.log(this); // console.log this to see what it is
}
aboutThis();  // call function
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}
undefined
// window

About the code above - this points window here. this points an object that calls function. window is running in global and the function aboutThis() is called in window. therefore, this points window.

let myObj = {
  val1:100,
  func1: function() { 
    console.log(this)
 }
}
myObj.func1();
// { val1: 100, func1: f}

there is function func1 inside object called myObj.
Image description
Then why console.log(this) prints {val1: 100, func1: f} ? it's because {val1: 100, func1: f} itself is myObj.

Closure

Scope is like effective range for variable(think about scope of sniper's rifle). let and const are block scoped. Global scope is like open space, you can access from anywhere.
I wrote about scope before. check

closure is like a space that's shut down or cannot access.

function myFunction() {
 var val1 ="hello"; // This area inside of function is closure space
}

function myFunction() {
 var val1 ="hello”;
return val1; 
}

function myFunction() {
var val1 ="hello";
return 10;
}

myFunction();
// 10

// If you'd like to take a value out of function, make it returns. You can take the value that's returned.

// You can also return object in function.
function myFunction() {
var val1 ="hello";
return { getVal1 : function(){} } 
}

function myFunction() {
var val1 ="hello";
return { getVal1 : function(){
          return val1; } 
  } 
}
// to access the value where it's in a place that's not allowed to access,
you can assign function to object and return
let result = myFunction();
result.getVal1();
// 'hello'

Why is there closure?
It's to avoid variables getting mixed and being polluted.

Image description
You can return object as well.
Something to read
More about closure

DOM basic

Document Object Model - about DOM

DOM practice

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <style>
        .container {
            display: flex;
            flex-direction: column;
            text-align: center;
            justify-content: center;
            align-items: center;
            margin-top: 50px;
        }

        .circle {
            width: 300px;
            height: 300px;
            border-radius: 50%;
            background-color: black;
            margin-bottom: 50px;
        }

        .btn-cont {
            display: flex;
        }

        button {
            /* padding: 16px 0; */
            width: 90px;
            height: 42px;
            display: flex;
            margin: 10px;
            align-items: center;
            justify-content: center;
            background-color: black;
            color: white;
            font-weight: 600;
            border-radius: 14px;
            border: 1px solid black;
            box-shadow: 0px 1px 1px 1px rgba(0, 0, 0, 0.4);
            cursor: pointer;
        }

        button:active {
            transform: scale(0.98);
        }

        .circle.red-bg {
            background-color: #ff324e;
        }

        .circle.yellow-bg {
            background-color: #ffff56;
        }

        .circle.green-bg {
            background-color: #55d600;
        }
    </style>
</head>

<body>
    <div>
        <div class="container">
            <div class="circle"></div>
            <div class="btn-cont">
                <button class="red-btn">RED</button>
                <button class="yellow-btn">YELLOW</button>
                <button class="green-btn">GREEN</button>
            </div>
        </div>
    </div>
    <script>
        const circle = document.querySelector(".circle");
        const btnRed = document.querySelector(".red-btn");
        const btnYellow = document.querySelector(".yellow-btn");
        const btnGreen = document.querySelector(".green-btn");

        // refactored code
        let btnArr = [btnRed, btnYellow, btnGreen];
        btnArr.forEach((item) => {
            item.addEventListener("click", () => {
                // circle.classList.remove("red-bg", "yellow-bg", "green-bg");
                circle.classList = "circle";
                if (item.className === "red-btn") {
                    console.log("cllicke")
                    circle.classList.add("red-bg");
                } else if (item.className === "yellow-btn") {
                    circle.classList.add("yellow-bg");
                } else {
                    circle.classList.add("green-bg");
                }

            })
        })
        // btnRed.addEventListener("click", function () {
        //     circle.classList.remove("yellow-bg", "green-bg");
        //     circle.classList.add("red-bg");
        // })

        // btnYellow.addEventListener("click", function () {
        //     circle.classList.remove("red-bg", "green-bg");
        //     circle.classList.add("yellow-bg");
        // })

        // btnGreen.addEventListener("click", function () {
        //     circle.classList.add("green-bg");
        //     circle.classList.remove("red-bg", "yellow-bg");

        // })

    </script>
</body>

</html>

Источник: dev.to

Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.

this closure dom javascript