상세 컨텐츠

본문 제목

클래스와 함수의 관계

Front-End/Javascript

by devloper-jun 2024. 4. 21. 20:17

본문

- ES6 이전에는 프로토 타입을 활용해 클래스의 작동 방식을 동일하게 구현.

/* Class */
class Cat {
	constructor(name) {
    	this.name = name
    }
    
    meow() {
    	console.log(`${this.name} 야옹`)
    }
    
    static hello() {
    	console.log('안녕')
    }
    
    set age(value) {
    	this.catAge = value
    }
    
    get age {
    	return this.catAge
    }
    
}
/* babel로 변환 */
'use strict'

// class가 function처럼 호출되는 것 방지
function _classCallCheck(instance, Constructor) {
	if(!(instance instanceof Constructor)) {
    	throw new TypeError(`Cannot call a class as a function`)
    }
}

// property 할당
function _defineProperties(target, props) {
	for(var i=0; i < props.length; i++) {
    	var descriptor = props[i]
    	descriptor.enumerable = descriptor.enumerable || false
        descriptor.configurable = true 
        if(`value` in descriptor) descriptor.writable = true
        Object.defineProperty(target, descriptor.key, descriptor)
	}    
}

// prototype method, static method
function _createClass(Constructor, protoProps, staticProps) {
	if(protoProps) _defineProperties(Constructor.prototype, protoProps)
    if(staticProps) _defineProperties(Constructor, staticProps)
    Object.defineProperty(Constructor, 'prototype', {writeable: false})
    return Constructor
}

var Cat = /*#__PURE__*/ (function () {
	function Cat(name) {
    	_classCallCheck(this, Cat)
        
        this.name = name
    }
    
    _createClass(
    	Cat,
        [
            {
				key: 'meow',
                value: function meow() {
                	console.log(
                    	''.concat(
                        	this.name,
                            '\...',
                        )
                    )
                }
            },
            {
            	key: 'age',
                get: function get() {
                	return this.catAge
                },
                set: function set(value) {
                	this.catAge = value
                },
            },
            {
            	key: 'hello',
                value: function hello() {
                	console.log('안녕')
                },
            },
        ],
    )
    
    return Cat
})()

- ES6 미만 환경에서는 동작하지 않는 클래스를 위해 _createClass라는 헬퍼 함수를 만들어 클래스와동일한 방식으로 동작할 수 있게 변경.

 

/* 보기 쉽게 변경 */
var Cat = (function() {
	function Cat(name) {
    	this.name = name
    }
    
    // prototype method 프로토타입에 할당하여 프로토타입 메서드로 동작
    Cat.prototype.meow = function () {
    	console.log(`...`)
    }
    
    // static method. instance 생성 없이 호출 가능하므로 직접 할당.
    Cat.hello = function () {
    	console.log('안녕')
    }
    
    // Cat 객체에 속성을 직접 정의
    object.defineProperty(Cat, 'age', {
    	// get, set은 각각 접근자, 설정자로 사용할 수 있는 예약어
        // getter
        get: function () {
        	return this.catAge
        },
        set: function (value) {
        	this.catAge = value
        },
    })
    
    return Cat
})()

- 클래스 작동을 생성자 함수로 유사하게 재현 가능함.

- 객체지향 언어를 사용하는 프로그래머가 좀 더 자바스크립트에 접근하기 쉬워지도록 한다고 볼 수 있으며, 자바스크립트 클래스가 프로토타입을 기반으로 작동한다는 사실 확인할 수 있음.

관련글 더보기