Chapter 06 - norux/javascript_study GitHub Wiki

6. 객체지ν–₯ ν”„λ‘œκ·Έλž˜λ°

μžλ°”μŠ€ν¬λ¦½νŠΈ μ—­μ‹œ λ‹€μŒ νŠΉμ„±μ„ κ°€μ§€λŠ” 객체지ν–₯ ν”„λ‘œκ·Έλž˜λ°μ΄ κ°€λŠ₯ν•˜λ‹€.

객체지ν–₯ μ–Έμ–΄μ˜ νŠΉμ„±

  • 클래슀, μƒμ„±μž, λ©”μ„œλ“œ
  • 상속
  • μΊ‘μŠν™”

클래슀기반의 언어와 ν”„λ‘œν† κΈ°λ°˜ μ–Έμ–΄

  • java, c++κ³Ό 같은 μ–Έμ–΄κ°€ 클래슀 기반의 언어이닀.
  • javascriptλŠ” ν”„λ‘œν† νƒ€μž… 기반의 언어이닀.

6.1 클래슀, μƒμ„±μž, λ©”μ„œλ“œ

  • java, c++μ—μ„œλŠ” classλΌλŠ” ν‚€μ›Œλ“œλ₯Ό 톡해 클래슀λ₯Ό λ§Œλ“€μ–΄ λ‚Έλ‹€.
  • μžλ°”μŠ€ν¬λ¦½νŠΈλŠ” ν•¨μˆ˜ 객체λ₯Ό μ΄μš©ν•˜μ—¬, 클래슀, μƒμ„±μž, λ©”μ„œλ“œλ₯Ό κ΅¬ν˜„ν•œλ‹€.

μ˜ˆμ œμ½”λ“œ

function Person(arg) {
  this.name = arg;

  this.getName = function() {
    return this.name;
  }

  this.setName = function( value ) {
    this.name = value;
  }
}

var me = new Person( "heebum" );
console.log( me.getName() );  // heebum

me.setName( "noru" );
console.log( me.getName() ); // noru


//이 μ½”λ“œμ˜ 문제점
var me = new Person( "me" );
var you = new Person( "you" );
var him = new Person( "him" );

  • λͺ¨λ“  μ€‘λ³΅λ˜λŠ” ν•¨μˆ˜λ“€μ„ λ©”λͺ¨λ¦¬μ— μ˜¬λ €λ†“κ³  μ‚¬μš©ν•˜κ²Œ λœλ‹€.
  • 이λ₯Ό ν•΄κ²°ν•˜λŠ” μ½”λ“œλŠ” λ‹€μŒκ³Ό κ°™λ‹€.
function Person( arg ) {
  this.name = arg;
}

Person.prototype.getName = function() {
   return this.name;
}
Person.prototype.setName = function( value ) {
  this.name = value;
}

var me = new Person( "me" );
var you = new Person( "you" );