Stack/JavaScript

[JS] 생성자 함수 복습

7ingout 2022. 8. 22. 14:53

constructorFunction.html

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
    <script>
        let user1 = {
            name: "green",
            age: 20,
            print: function() {
                console.log("hi")
            }
        }
        console.log(user1.name)
        user1.print();
        // 생성자 함수
        function User(name, age) {
            // this = {};
            this.name = name;
            this.age = age;
            this.print = () => {
                console.log(`내 이름은 ${this.name}입니다.`)
            }
            // return this;
        }
        let user2 = new User("blue", 33)
        user2.print();
    </script>
</body>
</html>