/ FRONTEND

클린코드 자바스크립트 6-2 객체 다루기(Prototype 조작 지양하기, hasOwnProperty, 직접 접근 지양하기)

Clean Code JS 강좌는 여러 절로 구성되어 있습니다.

객체 다루기 😎

Prototype 조작 지양하기👍

  • 이미 JS는 많이 발전했다.
    1. 직접 만들어서 모듈화 => 배포 => NPM
    2. JS 빌트인 객체를 건들지말자.

function Car {

  this.name = name;
  this.brand = brand;


  Car.prototype.sayName = function () {
    return this.brand + "-" + this.name;
  }
}

class Car {
  constructor(name, band) {
    this.name = name;
    this.brand = brand;
  }

  sayName() {
    return this.brand + "-" + this.name;
  }
}

const casper = new Car('캐스퍼','현대')
String.prototpye.welcome = function () {
  return "hello";
};

console.log("str".welcome()); // 'hello' 매우 위험한 것

Array.prototype.forEach = function () {
  return "hello";
};

console.log([].forEach()); // 'hello'

hasOwnProperty👍

  • 다른 객체에 있는 hasOwnProperty를 불러올 수도 있다.
  • 프로퍼티 명칭으로서 보호하지 않는다.
const person = {
  name: "john",
};

person.hasOwnProperty("name"); // true

for (const key in object) {
  if (Object.hasOwnProperty.call(object, key)) {
    const element = object[key];
  }
}

const foo = {
  hasOwnProperty: function () {
    return "hasOwnProperty";
  },
  bar: "string",
};

foo.hasOwnProperty('bar') // 'hasOwnProperty'

console.log(Object.prototype.hasOwnProperty.call(foo.'bar')) // true

// 함수를 따로 만들어 사용
function hasOwnProp(targetObj,targetProp) {
 return Object.hasOwnProperty.call(targetObj, targetProp);
}

console.log(hasOwnProp(foo,'bar')); //true

직접 접근 지양하기👍

  • 예측 가능한 코드를 작성해서 동작이 예측 가능하게 앱 구현
  • getter, setter
const model = {
  isLogin: false,
  isValidToken: false,
};

function setLogin(bool) {
  model.isLogin = bool;
}

function setValidToken(bool) {
  model.isValidToken = bool;
}

// model에 대신 접근 O
// function login() {
//   model.isLogin = true;
//   model.isValidToken = true;
// }

// function logout() {
//   model.isLogin = false;
//   model.isValidToken = false;
// }

// model에 대신 접근 X
function login() {
  setLogin(true);
  setValidToken(true);
}

function logout() {
  setLogin(false);
  setValidToken(false);
}

someElement.addEventListener("click", login);