Hi

클래스, 생성자, 메서드 본문

WEB(웹)/javascript

클래스, 생성자, 메서드

SharingWorld 2018. 7. 7. 18:25

클래스, 생성자, 메서드

자바스크립트는 거의 모든 것이 객체이고, 특히 함수 객체로 많은 것을 구현해낸다.


클래스, 생성자, 메서드도 모두 함수로 구현이 가능하다.

function Person(arg) {  
    this.name = arg;  
  
	this.getName = function() {  
	    return this.name;  
	};  
  
    this.setName = function(value) {  
        this.name = value;  
    }  
}  
  
var me = new Person("zzoon");  
console.log(me.getName()); // (출력값) zzoon  
  
me.setName("iamhjoo");  
console.log(me.getName()); // (출력값) iamhjoo

클래스 및 생성자의 역할을 하는 함수가 있고, 사용자는 new 키워드로 인스턴스를 생성하여 사용할 수 있다.


하지만 이 예제는 자원 낭비를 가져온다. 함수 객체의 프로토타입의 특성을 이용해 해결한다.

function Person(arg) {  
    this.name = arg;  
}  
  
Person.prototype.getName = function() {  
    return this.name;  
};  
  
Person.prototype.setName = function(value) {  
    this.name = value;  
};  
  
var me = new Person("me");  
var you = new Person("you");  
  
console.log(me.getName()); // me  
console.log(you.getName()); // you

클래스 안의 메서드를 정의할 때는 프로토타입 객체에 정의한 후, new로 생성한 객체에서 접근할 수 있게 하는 것이 좋다.


클래스 메서드를 정의하는 방법

Function.prototype.method = function(name, func) {
	if (!this.prototype[name]) {
		this.prototype[name] = func;
	}
}


ex)

Function.prototype.method = function(name, func) {  
    this.prototype[name] = func;  
};  
  
function Person(arg) {  
    this.name = arg;  
}  
  
Person.method("setName", function(value) {  
    this.name = value;  
});  
  
Person.method("getName", function() {  
    return this.name;  
});  
  
var me = new Person("me");  
var you = new Person("you");  
console.log(me.getName());  
console.log(you.getName());


'WEB(웹) > javascript' 카테고리의 다른 글

함수형 프로그래밍의 개념  (0) 2018.07.09
상속  (0) 2018.07.08
클래스 기반 언어와 프로토타입 기반 언어  (0) 2018.07.07
클로저  (0) 2018.07.07
join(), split(), includes()  (0) 2018.07.04