설명
모든 JavaScript 객체는 'prototype'이라는 내부 속성을 가지고 있다.
프로토타입(prototype)은 객체가 속성과 메소드를 상속할 수 있는 다른 객체를 가리킨다.
모든 객체는 상위 객체인 프로토타입을 갖고 있다.
prototype에 속성 추가
const a = new Number(10);
a.sample = 9;
console.log(a.sample); // 9
const b = new Number(200);
console.log(b.sample); // undefined
Number 객체 자료형 변수가 모두 공유하고 싶은 값은 prototype에 설정하면 된다.
Number.prototype.pi = 3.14;
console.log(a.pi); // 3.14
console.log(b.pi); // 3.14
// number 값에 대한 prototype 상속 발생
const i = 99;
console.log(i.pi); // 3.14
Number 객체의 prototype에 pi 속성을 추가하여 모든 Number 객체가 이 값을 공유할 수 있도록 한다.
이는 Number 객체가 prototype 체인을 통해 이 값을 상속받았기 때문이다.
i에 대해 i.pi를 호출할 때, 자바스크립트 엔진은 i를 Number 객체로 변환하여 pi 속성에 접근한다.
그러나 i는 객체가 아니기 때문에 실제로는 일시적인 객체로 변환되는 것이다.
그리고 이렇게 생성된 객체는 Number.prototype의 속성을 받으므로 3.14를 출력한다.
prototype 확장하여 사용자 정의 함수
Number.prototype.power = fucnction(n=2) { // 인자 기본값 2로 설정
return this.valueOf() ** n;
}
const a = 12;
console.log('a.power():' + a.power()); // 12 제곱값
console.log('a.power(3):' + a.power(3)); // 12 세제곱값
console.log('a.power(4):' + a.power(4)); // 12 네제곱값
this.valueOf()
객체를 원시 값으로 변환하는 메소드이다.
String.prototype.contain = function(data){
return this.indexOf(data) >= 0;
}
Array.prototype.contain = function(data){
return this.indexOf(data) >= 0;
}
const a = '안녕하세요';
console.log('안녕 in 안녕하세요 : ', a.contain('안녕')); // true
console.log('korea in 안녕하세요 : ', a.contain('korea')); // false
const b = [273, 32, 103, 75, 33];
console.log('103 in b : ' + b.contain(103)); // true
console.log('100 in b : ' + b.contain(100)); // false
indexOf()
문자열이나 배열에서 특정 데이터가 처음으로 발견되는 인덱스를 반환한다.
만약 데이터가 발견되지 않으면 -1을 반환한다.
'JS' 카테고리의 다른 글
document.body.innerHTML (0) | 2024.03.13 |
---|---|
배열에 속성 추가(?) (0) | 2024.03.12 |
object (0) | 2024.03.12 |
inner function (1) | 2024.03.11 |
declarative function | anonymous function (0) | 2024.03.11 |