[JS] class ๋ฌธ๋ฒ•

Hยท2022๋…„ 8์›” 4์ผ
0

๐Ÿ‘ฉโ€๐Ÿ’ป

๋ชฉ๋ก ๋ณด๊ธฐ
3/4

๐Ÿ“ขclass ๋ฌธ๋ฒ•

ํด๋ž˜์Šค๋Š” ๊ฐ์ฒด ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์—์„œ ํŠน์ • ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ธฐ ์œ„ํ•ด ๋ณ€์ˆ˜์™€ ๋ฉ”์†Œ๋“œ๋ฅผ ์ •์˜ํ•˜๋Š” ์ผ์ข…์˜ ํ‹€๋กœ, ๊ฐ์ฒด๋ฅผ ์ •์˜ํ•˜๊ธฐ ์œ„ํ•œ ์ƒํƒœ(๋ฉค๋ฒ„ ๋ณ€์ˆ˜)์™€ ๋ฉ”์„œ๋“œ(ํ•จ์ˆ˜)๋กœ ๊ตฌ์„ฑ๋œ๋‹ค.


โœจ ๊ธฐ๋ณธ ๋ฌธ๋ฒ•

๐Ÿ”  class๋Š” property , method๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค.

class Person{
  	name = 'name' // property : class์— ์ •์˜ํ•œ ํ•จ์ˆ˜
	call = () =>{...} // ํด๋ž˜์Šค์— ์ •์˜ํ•œ ๋ณ€์ˆ˜ 
}

๐Ÿ”  new ํ‚ค์›Œ๋“œ๋กœ ํด๋ž˜์Šค์™€ ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ

const myPerson = new Person(); 
myPerson.call();
consol.log(myPerson.name)

new Person()์œผ๋กœ ํ˜ธ์ถœํ•˜๋ฉด ๋‚ด๋ถ€์— ์ •์˜๋œ ๋ฉ”์„œ๋“œ๊ฐ€ ๋“ค์–ด์žˆ๋Š” ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋จ

์˜ˆ์‹œ

    class Test {
        constructor(value) {
            this.value = value
        }
        testFunc (){
            console.log(this.value)
        }
    }
    const test = new Test("๋‚ด๊ฐ€ ๋ณ€๊ฒฝํ•  ๊ฐ’");
    test.testFunc();
  1. ์ƒˆ๋กœ์šด ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋จ
  2. ๋„˜๊ฒจ๋ฐ›์€ ์ธ์ˆ˜์™€ ํ•จ๊ป˜ constructor๊ฐ€ ์ž๋™ ์‹คํ–‰
    new Test('๋‚ด๊ฐ€ ๋ณ€๊ฒฝํ•  ๊ฐ’') ์€ this.value์— ํ• ๋‹น๋œ๋‹ค.
  3. ํ• ๋‹น ํ›„ ํ•˜๋‹จ์˜ ๊ฐ์ฒด ๋ฉ”์„œ๋“œ๊ฐ€ ์‹คํ–‰๋จ.

super ํ‚ค์›Œ๋“œ ์‚ฌ์šฉํ•˜๊ธฐ

๐Ÿ”  super๋Š” ๋ถ€๋ชจ ์˜ค๋ธŒ์ ํŠธ์˜ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ ์‹œํ‚ฌ ๋•Œ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

    class Test {
        constructor() {
            this.test= "test"
        }
        testFunc (){
            console.log(this.test)
        }
    }

    class Test2 extends Test{
        constructor() {
          super();
            this.name = "name"
            this.test = "test2"
        }
        testFunc2 (){
            console.log(this.test)
        }
    }
    const test2 = new Test2();
    test2.testFunc();
    test2.testFunc2(); 

์œ„์—์„œ ์„ ์–ธํ•œ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์˜ฌ ๋•Œ super๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ฐ’์„ ๊ฐ€์ ธ ์˜จ ํ›„
Test์—์„œ ์„ ์–ธ๋œ this.test์˜ ๊ฐ’์„ Test2์—์„œ ๋ฐ”๊ฟ”์ค€๋‹ค.

ES7

๐Ÿ”  this๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , class์— property ๋ฐ”๋กœ ํ• ๋‹นํ•˜๊ธฐ

//๊ธฐ์กด ES6 ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด์•ผํ•จ 
//property
constructor(){
	this.testProperty = 'value '
}
//method
testMethod(){...}

//ES7 ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜์ง€ ์•Š์•„๋„ ๋จ
//property
testproperty = 'value'
// methode
testMethod = () => {...}

์˜ˆ์‹œ

    class Test {
    	test= "test"
		testFunc = () => {
        	console.log(this.test)
        } 
    }

    class Test2 extends Test{
		name = "name"
		test = "test2"
        testFunc2 = () => {
            console.log(this.test)
        }
    }
    const test2 = new Test2();
    test2.testFunc();
    test2.testFunc2(); 
profile
๐Ÿค˜ ๋Œ๋จธ๋ฆฌ๋„ ROCK์ด๋‹ค! ๐Ÿค˜

0๊ฐœ์˜ ๋Œ“๊ธ€