- JavaScript에서
hasOwnProperty는 객체가 특정 프로퍼티를 직접 소유하고 있는지 확인하는 메서드이다.Object.prototype에 정의되어 있으며, 모든 객체가 상속받아 사용할 수 있다.hasOwnProperty의 주요 사용목적은 객체가 특정 키를 자신의 직접적인 속성으로 가지고 있는지 확인하는 것으로, 트로토타입 페인을 통해 상속된 속성은 검사하지 않는다.
obj.hasOwnProperty(prop)
여기서 obj는 검사하고자하는 객체이고, prop은 문자열 형태의 프로퍼티 이름이다.
객체의 직접 정의된 속성을 확인하고, 프로토타입 체인을 통해 상속된 속성을 제외하려 할 때 사용한다.
ex)function MyObject() { this.myProperty = 'value'; } MyObject.prototype.myPrototypeProperty = 'inherited value'; const instance = new MyObject(); console.log(instance.hasOwnProperty('myProperty')); // true console.log(instance.hasOwnProperty('myPrototypeProperty')); // false
hasOwnProperty는 항상 정확하게 그 객체가 소유한 속성만을 확인한다.hasOwnProperty를 오버라이드 했을 가능성이 있다.Object.prototype.hasOwnProperty.call(obj, prop)방식을 사용하여 원본 함수를 직접 호출함으로써 안전하게 속성 존재 여부를 검사할 수 있다.hasOwnProperty는 객체 자체에 정의된 속성만을 확인한다.hasOwnProperty를 사용한 검사 결과에 영항을 준다const solution = (s) => {
const result = s.split("").reduce(
(acc, char, i) => {
// 현재 문자가 last에 이미 등장한 적이 있는 경우.
// last에서 그 문자의 마지막 인덱스를 찾아
// 현재 인덱스와의 차이를 계산하고 output에 추가한다
if (acc.last.hasOwnProperty(char)) {
acc.output.push(i - acc.last[char]);
} else {
acc.output.push(-1);
}
acc.last[char] = i;
return acc;
},
{ last: {}, output: [] }
);
return result.output;
};
const solution = (s) => {
const result = s.split("").reduce(
(acc, char, i) => {
// Object.prototype.hasOwnProperty.call을 사용하여 안전하게 확인
if (Object.prototype.hasOwnProperty.call(acc.last, char)) {
acc.output.push(i - acc.last[char]);
} else {
acc.output.push(-1);
}
acc.last[char] = i;
return acc;
},
{ last: {}, output: [] }
);
return result.output;
};
hasOnwProperty메소드를 안전하게 호출하여, 현재 문자가 last에 있는지 확인한다.Object.prototype.hasOwnProperty.call()과 같은 기능을 수행하지만, 보다 직관적이고 사용하기 쉽다const solution = (s) => {
const result = s.split("").reduce(
(acc, char, i) => {
// Object.hasOwn을 사용하여 안전하게 확인
if (Object.hasOwn(acc.last, char)) {
acc.output.push(i - acc.last[char]);
} else {
acc.output.push(-1);
}
acc.last[char] = i;
return acc;
},
{ last: {}, output: [] }
);
return result.output;
};
const solution = (s) => {
const result = s.split("").reduce(
(acc, char, i) => {
// 'in' 연산자를 사용하여 속성 존재 여부 확인
if (char in acc.last) {
acc.output.push(i - acc.last[char]);
} else {
acc.output.push(-1);
}
acc.last[char] = i;
return acc;
},
{ last: {}, output: [] }
);
return result.output;
};
in 연산자를 사용하면 대안으로 적용할 수 있지만, 차이점이 있다in은 객체의 자체 속성뿐만 아니라 프로토타입 체인을 통해 상속받는 속성도 검사한다.{}객체를 사용하는 경우, 프로토타입 속성으로 인한 문제가 일반적으로 발생하지는 않는다.const solution = (s) => {
const result = s.split("").reduce(
(acc, char, i) => {
// Reflect.has를 사용하여 속성 존재 여부 확인
if (Reflect.has(acc.last, char)) {
acc.output.push(i - acc.last[char]);
} else {
acc.output.push(-1);
}
acc.last[char] = i;
return acc;
},
{ last: {}, output: [] }
);
return result.output;
};