TIL-JavaScript(상속의 기능,prototype,표준 내장객체,배열의 확장)

연시아·2022년 6월 9일
0

TIL

목록 보기
36/51
post-thumbnail

22.06.09

🖐🏻 상속의 기능 추가

상속의 목적 : 상위 객체의 코드를 물려받아 하위 객체에 없는 프로퍼티도 사용할 수 있게 하기 위함입니다.

function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name; 
}
 function Programmer(name){      //생성자->programmer를 통해서 만든 객체가 person을 통해서 만든 객체와 동일한 기능을 가지도록 하는 것이 목적
    this.name = name;     // 사람이 가지고 있는 프로퍼티
}
Programmer.prototype = new Person();     // person이라는 객체는 prototype의 값이 되는 것이다-> 어떠한 객체를 상속받고 싶다면 그 객체를 생성자의 prototype에 할당을 시킨다.
Programmer.prototype.coding = function(){
    return "hello world";
}
 var p1 = new Programmer('egoing');      // 객체를 생성(인자 전달), p1은 prototype라는 생성자의 프로퍼타에 들어있는 객체와 같은데 그 객체는 new person, 즉 person이라는 생성자를 통해 만든 객체이기 때문에 그 객체가 가지고 있는 name과 introduce도 가지고 있다. 그래서 코드를 물려받아 사용할 수 있다.
document.write(p1.introduce()+"<br />");    // programmer라는 생성자 안에는 introduce라는 메소드가 정의되어 있지 않음->person 생성자에 정의되어 있음
document.write(p1.coding()+"<br />");   // programmer에서 introduce를 사용할 수 있았던 이유는 이 programmer가 introduce를 상속하기 때문이다.

programmer이라는 생성자들 만들었습니다. 그리고 이 생성자의 prototype과 person의 객체를 연결했더니 programmer 객체도 메소드 introduce를 사용할 수 있게 되었습니다. programmer가 person의 기능을 상속하는 있는 것입니다. 단순이 똑같은 기능을 갖게 되는 것이라면 상속의 의의는 사라질 것입니다. 부모의 기능을 계승 발전할 수 있는 것이 상속의 가치입니다.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name; 
}
 function Programmer(name){
    this.name = name;
}
Programmer.prototype = new Person();
Programmer.prototype.coding = function(){
    return "beautiful!";
}
 function Designer(name){
    this.name = name;
}
Designer.prototype = new Person();
Designer.prototype.design = function(){
    return "hello world";
}
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />");
document.write(p1.coding()+"<br />");
var p2 = new Designer('sia');
document.write(p2.introduce()+"<br />");
document.write(p2.design()+"<br />");
</script>
</body>
</html>

My name is egoing
beautiful!
My name is sia
hello world

결과는 이렇게 출력이 됩니다.

🤞🏻 prototype

한국어로는 원형정도로 변역되는 prototype은 말 그대로 객체의 원형이라고 할 수 있습니다. 함수는 객체입니다. 그러므로 생성자로 사용될 함수도 객체입니다. 객체는 프로퍼티를 가질 수 있는데 prototype이라는 프로퍼티는 그 용도가 약속되어 있는 특수한 프로퍼티입니다. prototype에 저장된 속성들은 생성자를 통해서 객체가 만들어질 때 그 객체에 연결됩니다.

function Ultra(){}
Ultra.prototype.ultraProp = true;
 function Super(){}
Super.prototype = new Ultra();
 function Sub(){}
Sub.prototype = new Super();    
 var o = new Sub();     // new를 붙이게 될 경우 생성자 함수-> 새로운 객체를 만들어서 그 객체를 리턴하기 때문에 o라는 변수 안에는 new sub() 이 생성자를 통해서 만들어진 객체가 o안에 들어가게 된다. 
console.log(o.ultraProp);

서로가 서로를 연결하는데 있어서 이 것을 prototype chain이라고 불립니다.

👏🏻 prototype chain

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function Ultra(){}
Ultra.prototype.ultraProp = true;
 function Super(){}
Super.prototype = new Ultra();
 function Sub(){}     // sub라는 생성자에 prototype 객체를 찾아서 그 객체에 프로퍼티중에 ultraprop 객체가 있는지를 확인해서 있다면 그 값을 (o.ultraprop)에 돌려주기 때문에 2라는 값이 (o.ultraprop) 여기에 들어올 수 있게 된다.
Sub.prototype = new Super();
sub.prototype.ultraprop = 2;       // 결과 : 2
 var o = new Sub();
console.log(o.ultraProp);     // o라는 객체에서 ultraprop라는 프로퍼티가 있는지 확인한다.
</script>
</body>
</html>
  • 객체 o에서 ultraProp를 찾는다.
  • 없다면 sub.prototype.ultraProp를 찾는다.
  • 없다면 Super.prototype.ultraProp를 찾는다.
  • 없다면 Ultra.prototype.ultraProp를 찾는다.

👌🏻 표준 내장 객체의 확장

표준 내장 객체(Standard Built-in Object)는 자바스크립트가 기본적으로 가지고 있는 객체들을 의미합니다. 내장 객체가 중요한 이유는 프로그래밍을 하는데 기본적으로 필요한 도구들이기 때문입니다. 결국 프로그래밍이라는 것은 언어와 호스트 환경에 제공하는 기능들을 통해서 새로운 소프트웨어를 만들어내는 것이기 때문에 내장 객체에 대한 이해는 프로그래밍의 기본이라고 할 수 있습니다.
자바스크립트는 아래와 같은 내장 객체를 가지고 있습나다.

  • object
  • Function
  • Array
  • String
  • Boolean
  • Number
  • Math
  • Date
  • RegExp

🤟🏻 배열의 확장

아래의 코드는 배열에서 특정한 값을 랜덤하게 추출하는 코드입니다.

Tsukuba');
function getRandomValueFromArray(haystack){
    var index = Math.floor(haystack.length*Math.random());
    return haystack[index]; 
}
console.log(getRandomValueFromArray(arr));

함수 getRandom ValueFromArray 안의 Math.floor(arr.length*Math.random())을 주어 배열 객체 Array 안에 들어 있는 배열들을 랜덤하게 추출할 수 있도록 하였습니다.
arr.length을 주어 Array안에 들어 있는 배열들의 갯수를 세게 하였고 Math.random으로 최솟값 '0.9'일 때는 최대값으로 랜덤 범위를 줄 수 있습니다.
Math.floor는 소수점 이하를 제거하여 length을 이용한 Array 배열울 추출하는데 문제 없게 하였습니다.
함수 getRandomValueFromArray의 리턴 값으로 arr[index]을 주어 설정해둔 랜덤 추출한 값을 Array 배열에서 배열들이 나오도록 하였습니다.

Array.prototype.rand = function(){
    var index = Math.floor(this.length*Math.random());
    return this[index];
}
var arr = new Array('seoul','new york','ladarkh','pusan', 'Tsukuba');
console.log(arr.rand());

위의 코드는 함수를 배열 객체에 포함시켜 더 세련되게 코드를 수정시켰습니다. 마치 배열에 내장된 메소드인 것처럼 위의 기능을 사용할 수 있게 했습니다.
일단 prototype 함수를 이용하여 random 메소드의 정보를 new생성자를 이용해 만든 객체 Array와 연결해 주었습니다. 그래서 random 메소드 안의 this는 new 생성자를 이용해 만든 것인 Array 객체 자체를 가리키게 됩니다.

profile
backend developer

0개의 댓글