//ex n = 0; control = "wsdawsdassw"
function controlNumber(n, control) {
const controlKeys = [...control];
const operation = {
w: +1,
s: -1,
d: +10,
a: -10,
};
// hasOwnProperty --> 지금은 불필요해보일 지 모르지만
// 추후 이상한 프로퍼티값이 들어오는 걸 방지해줄듯
for (const controlKey of controlKeys) {
if (operation.hasOwnProperty(controlKey)) {
n += operation[controlKey];
}
}
return n;
}
여기에서 hasOwnProperty
의 역할은 보이는것과 같이, 정해지지 않은 프로퍼티 값이 들어오면 막아주는 역할을 한다.
이처럼 object.hasOwnPropery(property)를 통해 쉽게 그 프로퍼티가 있는지를 확인할 수 있었는데, 무엇이 문제일까?
아래의 예시를 보자.
const foo = {
hasOwnProperty : function(){
return "hasOwnProperty";
},
bar: 'Bar'
}
hasOwnProperty
라는 자신이 직접만든 함수를 가지고 있다.hasOwnProperty
처럼 사용한다면?console.log(foo.hasOwnProperty("bar")); // hasOwnProperty
Object.prototype 의 hasOwnProperty로 가서 Object 것을 쓴다고 명시하고 사용하는 방법이다.
console.log(Object.prototype.hasOwnProperty.call(foo, 'bar')) // true
hasOwnProperty
가 있어도 원래 사용하려했던 hasOwnProperty
를 사용할 수 있다.Object.prototype.hasOwnProperty.call 을 계속 작성하는것도 일이다. 이를 함수로 빼놓고 사용하는 방법이다.
function hasOwnProp(targetObj, targetProp){
return Object.prototype.hasOwnProperty.call(targetObj, targetProp)
}
hasOwnProp(foo, 'bar') //true
hasOwnProperty
를 대신해서 나온 것이 hasOwn
이다.const object1 = {
prop: 'exists',
};
console.log(Object.hasOwn(object1, 'prop'));
// Expected output: true
console.log(Object.hasOwn(object1, 'toString'));
// Expected output: false
위의 hasOwnProperty
의 문제를 hasOwn
으로 처리하게 된 것이다.
const foo = {
hasOwnProperty() {
return false;
},
bar: "The dragons be out of office",
};
if (Object.hasOwn(foo, "bar")) {
console.log(foo.bar); // true
}
그러면 맨 처음 예제로 봤던 알고리즘도 아래와 같이 바꿀 수 있다.
function solution(n, control) {
const controlKeys = [...control]
const operation = {
'w' : +1,
's' : -1,
'd': +10,
'a' : -10
}
for(const controlKey of controlKeys){
//hasOwnProperty 대신 hasOwn
if(Object.hasOwn(operation,controlKey)){
n += operation[controlKey]
}
}
return n
}
const fruits = ["Apple", "Banana", "Watermelon", "Orange"];
Object.hasOwn(fruits, 3); // true ('Orange')
Object.hasOwn(fruits, 4); // false - not defined
hasOwnProperty
대신hasOwn
을 쓰는게 맞나.. ?