class

class는 객체를 만들어내기위한 틀이다. class는 class 표현식과 class 선언식으로 만들어 낼 수 있다.

또한, 이전 문법으로는 function 과 this를 이용하여도 class를 만들었다.

 

this는 instance로, 새로 생성되는 object들을 가리킨다.

// function & this 를 이용한 class 선언

function Template(name : string, age : number, address : string ){
	this.name : name;
    this.age : age;
    this.address : address;
}

var Yeonji = new Teplate("Yeonji", 22, "Suwon");
class Template{
	constructor(name : string, age : number){
    	this.name = name;
        this.age = age;
    }
}

 

prototype

javascript는 prototype 기반의 언어이다. 상속관점에서 js의 유일한 생성자는 객체뿐이며, 이러한 객체는 prototype이라는 private 속성을 가진다. prototype은 chain의 형태로 존재하여 prototype이 null이 될때까지 prototype을 뒤지는 것을 반복한다. 만약 어떤 ob라는 object에 a라는 속성이 없는데 ob.a를 부른다면, js는 ob의 속성에 a가 있는지 찾고, 없다면 ob.[[Prototype]]의 속성에 a가 있는지 찾고 그래도 없다면 다시 ob.[[Prototype]].[[Prototype]]에서 a를 찾는다 만약 ob.[[Prototype]].[[Prototype]]이 null이라면 찾는 것을 그만두고 ob.a 는 undefined가 반환되는 것이다. 

 

var array = [5,43,6,2,1];
array.sort();
console.log(array);
// 결과 : 1,2,5,6,43

위와 같이 array에서 sort()라는 함수를 사용할 수 있는 이유는 prototype 때문이다. var array = [5,43,6,2,1]; new를 사용하여 선언하면 var array = new Array(5,43,6,2,1); 이 되는데, class의 자식을 선언한는 것과 같다. array변수의 Prototype은 Array로, Array의 Prototype이 가지고 있는 함수를 array 변수는 모두 사용할 수 있다. 그렇기 때문에 array의 Prototype인 Array의 Prototype에 존재하는 sort()라는 함수를 사용할 수 있는 것이다. 

 

내가 만든 함수를 여러 다른 함수가 속성으로 사용하게 하고 싶을 때도 prototype을 응용하면된다.

function ggFunction(){
	console.log("hello");
}

var gg = [1,2,3];
Array.prototype.Func = ggFunction;

gg.Func();

 

 

출처 :

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/class

https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Object_prototypes

https://developer.mozilla.org/ko/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85_%EC%B2%B4%EC%9D%B8%EC%9D%84_%EC%9D%B4%EC%9A%A9%ED%95%9C_%EC%83%81%EC%86%8D

728x90

+ Recent posts