Recent Posts
Recent Comments
Link
06-28 05:11
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

javascript class 본문

DEV&OPS/Javascript

javascript class

ALEPH.GEM 2022. 3. 15. 11:20

 

생성자

1. 함수의 선언문으로 정의

function Card(suit, rank){
    this.suit = suit;
    this.rank = rank;
}
Card.prototype.show = function(){
    console.log(this.suit + this.rank);
};

2. 함수 리터럴로 정의

var Card = function(suit, rank){
    this.suit = suit;
    this.rank = rank;
};
Card.prototype.show = function(){
    console.log(this.suit + this.rank);
};

3. 클래스 선언문으로 정의

class Card {
    constructor (suit, rank){
        this.suit = suit;
        this.rank = rank;
    }
    show(){
        console.log(this.suit + this.rank);
    }
}

4. 클래스 표현식으로 정의

var Card = class{
    constructor (suit, rank){
        this.suit = suit;
        this.rank = rank;
    }
    show(){
        console.log(this.suit + this.rank);
    }
};

2,3,4 로 정의한 생성자는 호출하기 전에 정의해야 합니다.

1로 정의하면 자바스크립트 엔진이 시작부분으로 끌어올려주기 때문에 나중에 정의해도 됩니다.

 

 

생성자로 접근자 프로퍼티 getter/setter 정의

function Person(name){
    Object.defineProperty(this, "name", {
        get: function(){
            return name;
        },
        set: fuction(newName){
            name = newName;
        },
        enumerable: true,
        configurable: true
    });
}
Person.prototype.sayName = function(){
    console.log(this.name);
};

var p = new Person("Tom");
console.log(p.name);	/* Tom */
p.name = "Huck";
console.log(p.name);	/* Huck */
p.sayName();			/* Huck */

 

 

수퍼 타입(super type) 생성자

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>

    <script>
        /* 타원 객체 */
        function Ellipse(a, b){
            this.a = a;     /* 장축 반지름 */
            this.b = b;     /* 단축 반지름 */
        }
        /* 타원 넓이 메서드 */
        Ellipse.prototype.getArea = function(){
            return Math.PI*this.a*this.b;
        };
        /* toString() 오버라이드 */
        Ellipse.prototype.toString = function(){
            return this.a + " " + this.b;
        }

        var ellipse = new Ellipse(5,3);
        console.log(ellipse.getArea());
        console.log(ellipse.toString());
    </script>
</body>
</html>
생성자의 prototype 상속
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        /* 타원 객체 */
        function Ellipse(a, b){
            this.a = a;     /* 장축 반지름 */
            this.b = b;     /* 단축 반지름 */
        }

        /* 타원 넓이 메서드 */
        Ellipse.prototype.getArea = function(){
            return Math.PI*this.a*this.b;
        };

        /* toString() 오버라이드 */
        Ellipse.prototype.toString = function(){
            return this.a + " " + this.b;
        }

        /* 원 객체 */
        function Circle(r){
            this.a = r;
            this.b = r;
        }

        /* 타원 객체로부터 생성자 상속 */
        Circle.prototype = Object.create(Ellipse.prototype, {
            constructor: {
                configurable: true,
                enumerable: true,
                value: Circle,
                writable: true
            }            
        });

        /* toString() 오버라이드 */
        Circle.prototype.toString = function(){
            return "Circle " + this.a + ", " + this.b;
        };

        /* 반지름 2인 circle 인스턴스 생성 */
        var circle = new Circle(2);
        /* 상속 받은 메서드 활용 */
        console.log(circle.getArea());
        console.log(circle.toString());
    </script>
</body>
</html>
또다른 상속 방법
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        /* 타원 객체 */
        function Ellipse(a, b){
            this.a = a;     /* 장축 반지름 */
            this.b = b;     /* 단축 반지름 */
        }

        /* 타원 넓이 메서드 */
        Ellipse.prototype.getArea = function(){
            return Math.PI*this.a*this.b;
        };

        /* toString() 오버라이드 */
        Ellipse.prototype.toString = function(){
            return this.a + " " + this.b;
        }

        /* 원 객체 */
        function Circle(r){
            this.a = r;
            this.b = r;
        }

        /* 타원 객체로부터 생성자 상속 */
        Circle.prototype = new Ellipse();
        Circle.prototype.constructor = Circle;

        var circle = new Circle(3);

        /* 상속 받은 메서드 활용 */
        console.log(circle.getArea());
        console.log(circle.toString());
    </script>
</body>
</html>
생성자 빌려오기
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        /* 타원 객체 */
        function Ellipse(a, b){
            this.a = a;     /* 장축 반지름 */
            this.b = b;     /* 단축 반지름 */
        }

        /* 타원 넓이 메서드 */
        Ellipse.prototype.getArea = function(){
            return Math.PI*this.a*this.b;
        };

        /* toString() 오버라이드 */
        Ellipse.prototype.toString = function(){
            return this.a + " " + this.b;
        }

        /* 원 생성자 */
        function Circle(r){
            /* 생성자 빌려오기 */
            Ellipse.call(this, r, r);
            /* 추가하거나 수정할 프로퍼티는 여기부터 작업 할 수 있음 */
        }

        /* 타원 객체로부터 생성자 상속 */
        Circle.prototype = Object.create(Ellipse.prototype, {
            constructor: {
                configurable: true,
                enumerable: true,
                value: Circle,
                writable: true
            }
        });

        /* toString 메서드 오버라이드 */
        Circle.prototype.toString = function(){
            return "Circle " + this.a + ", " + this.b;
        };

        var circle = new Circle(3);

        /* 상속 받은 메서드 활용 */
        console.log(circle.getArea());
        console.log(circle.toString());
    </script>
</body>
</html>
수퍼 타입 메서드 이용
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        /* 타원 객체 */
        function Ellipse(a, b){
            this.a = a;     /* 장축 반지름 */
            this.b = b;     /* 단축 반지름 */
        }

        /* 타원 넓이 메서드 */
        Ellipse.prototype.getArea = function(){
            return Math.PI*this.a*this.b;
        };

        /* toString() 오버라이드 */
        Ellipse.prototype.toString = function(){
            return this.a + " " + this.b;
        }

        /* 원 생성자 */
        function Circle(r){
            /* 생성자 빌려오기 */
            Ellipse.call(this, r, r);
            /* 추가하거나 수정할 프로퍼티는 여기부터 작업 할 수 있음 */
        }

        /* 타원 객체로부터 생성자 상속 */
        Circle.prototype = Object.create(Ellipse.prototype, {
            constructor: {
                configurable: true,
                enumerable: true,
                value: Circle,
                writable: true
            }
        });

        /* 수퍼 타입의 toString()을 이용한 정의 */
        Circle.prototype.toString = function(){
            var str = Ellipse.prototype.toString.call(this);
            return "Circle " + str.replace(" " , ",");
        };

        var circle = new Circle(3);

        /* 상속 받은 메서드 활용 */
        console.log(circle.getArea());
        console.log(circle.toString());
    </script>
</body>
</html>

 

 

클래스

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        /* 원 클래스 */
        class Circle {
            constructor(center, radius){
                this.center = center;
                this.radius = radius;
            }
            area(){
                return Math.PI*this.radius*this.radius;
            }
        }

        var circle = new Circle({x: 0, y: 0}, 2);

        /* 상속 받은 메서드 활용 */
        console.log(circle.area());
    </script>
</body>
</html>
클래스 구문으로 접근자 프로퍼티 getter / setter 작성 방법
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        class Person{
            constructor(name){
                this.name = name;
            }
            get name(){
                return this._name;
            }
            set name(value){
                this._name = value;
            }
            sayName(){
                console.log(this.name);
            }
        }

        var person = new Person("Tom");
        console.log(person.name);   /* Tom */
        person.name = "Huck";
        console.log(person.name);   /* Huck */
        person.sayName();   /* Huck */
    </script>
</body>
</html>
static
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        class Person{
            constructor(name){
                this.name = name;
                Person.personCount++;
            }
            get name(){
                return this._name;
            }
            set name(value){
                this._name = value;
            }
            sayName(){
                console.log(this.name);
            }
            static count(){
                return Person.personCount;
            }
        }
        Person.personCount = 0;

        var person1 = new Person("Tom");
        console.log(Person.count());   /* 1 */
        var person2 = new Person("Huck");
        console.log(Person.count());   /* 2 */
    </script>
</body>
</html>
extends 상속
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        class Circle{
            constructor(center, radius){
                this.center = center;
                this.radius = radius;
            }
            area(){
                return Math.PI*this.radius*this.radius;
            }
            toString(){
                return "Circle " + "중심 (" + this.center.x + "," +this.center.y + "), 반지름 ="+this.radius;
            }
        }
        class Ball extends Circle{
            move(dx, dy){
                this.center.x += dx;
                this.center.y += dy;
            }
        }
        var ball = new Ball({x: 0, y: 0}, 2);
        console.log(ball.toString());   /* 상속받은 메서드 */
        console.log(ball.area());       /* 상속받은 메서드 */
        ball.move(1,2); /* 상속받은 후 추가된 메서드 사용 가능 */
        console.log(ball.toString());
    </script>
</body>
</html>
super
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <script>
        class Circle{
            constructor(center, radius){
                this.center = center;
                this.radius = radius;
            }
            area(){
                return Math.PI*this.radius*this.radius;
            }
            toString(){
                return "Circle " + "중심 (" + this.center.x + "," +this.center.y + "), 반지름 ="+this.radius;
            }
        }
        class Ball extends Circle{
            move(dx, dy){
                this.center.x += dx;
                this.center.y += dy;
            }
            /* toString메서드 오버라이드 */
            toString(){
                var str = super.toString();
                return str.replace("Circle", "Ball");
            }
        }
        var ball = new Ball({x: 0, y: 0}, 2);
        console.log(ball.toString());   /* 오버라이드 하면서 Ball로 변경 */

    </script>
</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

728x90

'DEV&OPS > Javascript' 카테고리의 다른 글

javascript BLOB  (0) 2022.03.18
javascript 드래그 앤 드롭  (0) 2022.03.17
Ajax  (0) 2022.03.12
javascript 비동기 처리 Promise  (0) 2022.03.12
javascript event  (0) 2022.03.11