DEV Community

Dahye Ji
Dahye Ji

Posted on • Updated on

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

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]
Enter fullscreen mode Exit fullscreen mode

** 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'
Enter fullscreen mode Exit fullscreen mode

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)

Number, String, Boolean, undefined, null, Symbol are primitive type and Array, object and function are object/reference type.

Object

  • Object is instance of class in Object oriented programming. Javascript is prototype based - object oriented language. (which doesn't need class) However, Class has adopted in ES6.
  • Everything that consists of JavaScript is "Object" (except the primitive value, everything else is object)
  • Object is one or more of set of properties and properties have key-value pair.

Literal

JavaScript literals: literals are constant values that can be assigned to the variables that are called literals or constants. JavaScript literals are syntactic representations for different types of data like numeric, string, boolean, array, object, function etc data...

Instance

let myString = new String('hello world');
Enter fullscreen mode Exit fullscreen mode

myString is an instance that's pointing String here. myString here is also called as 'Object'
Object is called instance and instance also can be called object. Because when the Function constructor is creating object, object at that point is called instance.
Instance is a created result of Function constructor.
'hello world' from above code can be called as object literal/string/primitive value/instance...etc

Function constructor

function User(name) {
    this.name = name;
    this.isAdmin = false;
}
let user = new User('Violet');
console.log(user.name); // Violet
console.log(user.isAdmin); // false

let user = new User('Hailey');
user.name;
// 'Hailey'
Enter fullscreen mode Exit fullscreen mode

About function() constructor

this

When function or object executes the code, it points where the function or object is being executed. this points the execution context.

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
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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

this is window-2

/ * this */
function sayName(){
  console.log(this.name);
}

let name = 'Hero'; // globally declared variable name
// so this means window.name === "Hero"

let peter = {
  name : 'Peter Parker',
  sayName : sayName
}

let bruce = {
  name : 'Bruce Wayne',
  sayName : sayName
}

sayName();
peter.sayName(); 
// Peter Parker
bruce.sayName();
// Bruce Wayne
Enter fullscreen mode Exit fullscreen mode

Take a look at apply(), call(), bind() as well.

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/ 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 to return. 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'
Enter fullscreen mode Exit fullscreen mode

Why is there closure?
It's to avoid variables getting mixed and being polluted. Also, to keep it safe.

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

DOM basic

Document Object Model - about DOM
The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web
The Document Object Model (DOM) is a programming interface for web documents.
It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

How to access DOM tree

using document object, you can access to html document.

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>
Enter fullscreen mode Exit fullscreen mode

Discussion (0)