JavaScript

[모던 JavaScript] 4.5 과제 정리

보라해바라기 2022. 11. 25. 09:52
SMALL
  • 4.5 new 연산자와 생성자 함수

4.5 (1) 함수 두 개로 동일한 객체 만들기

<!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>함수 두 개로 동일한 객체 만들기</title>
</head>
<body>
    <script>
        // new A() == new B () 성립 가능
        // 두 함수에 return 객체 ! 삽입하기

        let obj = {};
        function A() { return obj; }
        function B() { return obj; }

        alert ( new A() == new B() )
    </script>
</body>
</html>

4.5 (2) 계산기 만들기

<!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>계산기 만들기</title>
</head>
<body>
    <script>
        function Calculator() {
            this.read = function() {
                this.a = +prompt("첫 번째 숫자", 0);
                this.b = +prompt("두 번째 숫자", 0);
            };

            this.sum = function() {
                return this.a + this.b;
            };

            this.mul = function() {
                return this.a * this.b;
            };
        }

        let calculator = new Calculator();
        calculator.read();

        alert( "Sum=" + calculator.sum() );
        alert( "Mul=" + calculator.mul() );
    </script>
</body>

4.5 (3) 누산기 만들기

<!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>누산기 만들기</title>
</head>
<body>
    <script>
        function Accumulator(startingValue) {
            this.value = startingValue;
            
            this.read = function() {
                return this.value += +prompt("더할 값을 입력하세요.", 0);
            };
        }

        let accumulator = new Accumulator(1);
        
        accumulator.read();
        accumulator.read();
        
        alert(accumulator.value);
    </script>
</body>
</html>
728x90