📁
til
  • TIL(Today I Learned)
  • javascript
    • value-number-string-boolean-null-undefined
    • primitive-reference
    • Hoisting
    • Prototypes in Javascript
    • this
    • prototype
    • 콜백함수 (Callback function)
    • 함수의 호출
    • 자료구조 new keyword
    • closure
    • Promise
    • event-loop
    • array-object
    • 객체
    • Arguments
    • higher order function
    • operators-function-control-flow
    • 객체 생성 패턴 3가지
    • Javascript scopes
    • Functional Programming
    • Design Patterns
    • 데이터 타입
    • Object 객체
    • 표준 내장 객체의 확장
    • 참조
    • 함수
    • 상속(Inheritance)
    • this - 'this'를 사용하는 해당 함수를 '어떻게' 실행하느냐에 따른 4가지 this 정의
    • 전역객체(Global object)
    • 객체 지향 프로그래밍
    • The 'new' keyword - Object Creation in JavaScript
  • javascript-api
    • Number
      • Number.MAX_VALUE
      • Number.isInteger
      • Number.NEGATIVE_INFINITY
      • Number.isNaN()
      • Number.POSITIVE_INFINITY
      • Number.parseFloat
      • Number.EPSILON
      • number.toExponential
      • Number.MAX_SAFE_INTEGER
      • Number1 - 자연수, 정수, 10진수, 2진수, 부동소수점, 실수
      • Number.isSafeInteger()
      • Number.MIN_VALUE
      • Number.parseInt
      • Number.NaN
      • Number.isFinite()
      • Number.MIN_SAFE_INTEGER
      • toFixed
    • string.split
    • String.fromCodePoint
    • string.trimEnd
    • string.padStart
    • string.@@iterator
    • String.fromCharCode
    • string.toUpperCase
    • string.codePointAt
    • string.toLowerCase()
    • string.toString
    • string.includes
    • string.replace()
    • string.charAt
    • String.lastIndexOf
    • string.slice
    • string.search
    • string.padEnd
    • string.substring
    • string.length
    • string.trim
    • string.localeCompare
    • String.indexOf
    • string.endsWith
    • string.valueOf
    • String.raw
    • string.matchAll()
    • string.repeat
    • string.match
    • String.prototype
    • string.startsWith
    • string.charCodeAt
    • string.trimStart
    • string.concat
    • string.toLocaleUpperCase()
    • string.toLocaleLowerCase
    • String
  • learn-node
    • debugger
    • Tip
  • schema-design
    • Database Schema Design
    • Database Schema Design
  • react
    • LifeCycle
    • redux
    • Context API
    • 함수형 컴포넌트와 클래스, 어떤 차이가 존재할까?
    • Hooks과 useEffect 사용해 보기
    • Route
    • async wait 사용하기
    • Hooks API Reference
    • context
    • npm uninstall 하는법
    • test 만들기
  • tip
    • 클린코드
    • BxSlider로 텍스트 흐르는 효과 만들기
  • javascript30
    • Event Capture, Propagation, Bubbling and Once
    • Object and Arrays - Reference VS Copy
  • typescript
    • 우아한 타입스크립트 2부
    • The Basic Cheatsheet
    • TypeScript
    • Type Guards and Differnetiating Types
    • 우아한 타입스크립트
    • Generics
  • git-from-the-hell
    • git
    • init-status-add-commit-log-stage-repository
    • log-diff
    • 머지 후 branch 삭제하기
    • 지옥에서 온 Git
    • reset-revert
    • develop branch 를 pull 하고 싶을때
  • conference-and-seminar
    • 모던 프론트엔드 개발환경의 이해
  • fire-base
    • Firebase .gitignore
  • vanillacoding
    • Data Structures
    • Sorting Algorithms - part 1
    • Promise
    • class
    • 04.quiz
    • 07.event-loop
    • Design Patterns
    • OOP (Object Oriented Programming)
  • etc
    • 알고리즘 코드리뷰
    • 스스로 공부하는 법
    • 바닐라코딩 수강 후기
    • async 과제 후기 - 비동기, 동기, 클로저, 배열과 객체
    • 유용한 사이트
  • algorithm
    • The Supermarket Queue
    • Find the odd int
    • The Office III - Broken Photocopier
    • Directions Reduction
    • The Office II - Boredom Score
    • Divisible Sum Pairs
    • Codewars 이용자 솔루션 모음
    • Shortest Word
    • find key
    • Two Sum
    • Simple Pig Latin
  • Book
    • the essence of object-orientation
      • 타입과 추상화
      • 객체 지도
      • 이상한 나라의 객체
      • 추상화 기법
      • 05. 책임과 메시지
      • 07.함께 모으기
      • 04. 역할, 책임, 협력
      • 협력하는 객체들의 공동체
  • ecma-script2015
    • Object Literal Upgrades
    • default-parameter-template-literals-arrow-functions
    • spread-operator-rest-param
    • let-const-rest-parameter-spread-operator-destructuring
  • http
    • 웹 브라우저에 URL을 입력했을 때 어떻게 웹 페이지가 보여질까?
  • jest
    • toThrow(error?)
  • data-structures
    • Data Structures
  • express
    • express generator
    • CORS
  • css-flexible-box-layout
    • flex 해버렸지 뭐야
  • git
    • Git
  • mongodb
    • MongoDB
  • markdown
    • use-markdown
  • cmder
    • cmd 명령어 모음
  • debug
    • trackClicksEx function error
  • npm
    • NPM TOKEN 설정하기
  • storybook
    • Storybook
  • sort
    • Sorting Algorithms - part 1
  • javascript-koans
    • Javascript Koans 오답노트
  • rxjs
    • Rx.js
  • dom-elements
    • HTML Element
  • redux-toolkit
    • Redux Toolkit
  • github-actions
    • GitHub Actions
  • redux-middleware
    • redux middleware
  • rest
    • rest
  • css-rendering
    • 코드 스피츠 - CSS Rendering 1회차 2/2
    • 코드 스피츠 - CSS Rendering 1회차 1/2
  • you-dont-know-js
    • 타입
  • server
    • # shutdown local server
  • semantic-versioning
    • Semantic Versioning 2.0.0
Powered by GitBook
On this page
  • Object의 생성자의 메소드와 Object의 프로토타입 객체
  • Object 객체 확장
  • Object 확장의 위험
  • 그래도 써야한다면 hasOwnProperty

Was this helpful?

  1. javascript

Object 객체

  • 연관있는 변수와 함수를 묶어준다.

  • prototype을 이용해 상속이 가능하다.

    • 이전 Ultra -> Super -> Sub 를 상속받던 예시에서 사실 Ultra는 Object를 상속받고 있다.

    • Object -> Ultra -> Super -> Sub

  • Object의 prototype은 모든객체의 prototype이다. 모든객체의 원형이다.

Object의 생성자의 메소드와 Object의 프로토타입 객체

// Object.keys() 생성자 메소드
var arr = ['a','b','c'];
console.log(Object.keys(arr));

//Object.prototype.toString() 프로토타입객체 
var a = new Array(1,2,3);
console.log(a.toSring());

1번과 2번의 사용방법이 왜 다를까? 1번 Object.keys()는 인자를 받아서 사용한다.

Object.key(arr) //의 Object는 생성자 함수일 것이고
Object.keys = function(){}; // 이렇게 정의되어 있을 것이다.

2번 Object.prototype.toString()은

Object.prototype.toSring = function(){};

이렇게 prototype으로 정의되어 있을 것이다.

메소드가 프로토타입이라는 의미는 new Object();라고 실행을 하는 순간에 어떠한 객체를 만들고 Object.prototype 이라는 특수한 프로퍼티의 저장되어 있는 객체를 원형으로 하는 객체가 생성된다. 그렇게 생성된 객체는 toString이라는 메소드를 쓸 수 있다.

이 두 차이를 이해해야 한다.

Object 객체 확장

Object.prototype.contain = function(needle){
    for(var name in this){
        if(this[name] === needle){
            return true;
        }
    }
    return false;
}

var o = {name: 'sla', 'city':'seoul'};
console.log(o.contain('sla'));

Object 확장의 위험

Object.prototype.contain = function(needle){
    for(var name in this){
        if(this[name] === needle){
            return true;
        }
    }
    return false;
}

var o = {name: 'sla', 'city':'seoul'};
//console.log(o.contain('sla'));

for(var name in o){
    console.log(o[name]);
} 

//결과는
/*
sla
seoul
ƒ (needle){
    for(var name in this){
        if(this[name] === needle){
            return true;
        }
    }
    return false;
}
*/

이렇게 contain 까지 같이 나온다. 모든 객체에 영향을 준거다.

Object.prototype.contain = function(needle){
    for(var name in this){
        if(this[name] === needle){
            return true;
        }
    }
    return false;
}

var o = {name: 'sla', 'city':'seoul'};
//console.log(o.contain('sla'));

for(var name in o){
    console.log(name);
} 
//결과
//name
//city
//contain

contain 이 포함되어 있다.

object에 프로퍼티에 추가한다는건 편리하면서도 위험하다.

그래도 써야한다면 hasOwnProperty

Object.prototype.contain = function(needle){
    for(var name in this){
        if(this[name] === needle){
            return true;
        }
    }
    return false;
}

var o = {name: 'sla', 'city':'seoul'};
//console.log(o.contain('sla'));

for(var name in o){
    if(o.hasOwnProperty(name)){
        console.log(name);    
    }
}

자신의 property인지 체크해준다. 부모로 부터 상속받은 것은 제외된다.

Previous데이터 타입Next표준 내장 객체의 확장

Last updated 5 years ago

Was this helpful?