Simple Inheritance with JavaScript - Lee-hyuna/33-js-concepts-kr GitHub Wiki

์›๋ฌธ ์ถœ์ฒ˜: https://www.sitepoint.com/simple-inheritance-javascript/

์ƒ์† ๊ตฌํ˜„

JavaScript๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ด ๊ณ„์ธต์œผ๋กœ ๋งŒ๋“ค๋ ค๋Š” ํ•ญ๋ชฉ์„ ์‹œ๊ฐํ™”ํ•ด๋ณด์ž.

์šฐ์„ , ClassA๋ฅผ ๋งŒ๋“ ๋‹ค. ๋ช…์‹œ์ ์ธ ํด๋ž˜์Šค๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์—, ์•„๋ž˜์™€ ๊ฐ™์€ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด๋ƒ„์œผ๋กœ์จ ์ •์˜ํ•  ์ˆ˜ ์žˆ๋‹ค.

var ClassA = function() {
  this.name = "class A";
}

"class"์— new Keyword๋กœ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค.

var a = new ClassA();
ClassA.prototype.print = function() {
    console.log(this.name);
}

๊ทธ๋ฆฌ๊ณ  a์— ์—ฐ๊ฒฐ๋œ object๋ฅผ ์ด์šฉํ•œ๋‹ค.

a.print();

๊ฝค ์‰ฝ์ฃ ?
์ด๋ฒˆ์—” ์•„์ฃผ ์งง์€ ์ฝ”๋“œ๋ฅผ ์†Œ๊ฐœํ•œ๋‹ค.

var ClassA = function() {
    this.name = "class A";
}

ClassA.prototype.print = function() {
    console.log(this.name);
}

var a = new ClassA();

a.print();

์ด์ œ ํด๋ž˜์Šค ์‚ฌ์ด์— "์ƒ์†์„ฑ"์„ ๋งŒ๋“œ๋Š” ๋„๊ตฌ๋ฅผ ์ถ”๊ฐ€ํ•ด๋ณด์ž. ์ด ํˆด์€ ํ•œ ๊ฐ€์ง€ ์ผ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค.
ํ”„๋กœํ† ํƒ€์ž… ๋ณต์ œ:

var inheritsFrom = function (child, parent) {
    child.prototype = Object.create(parent.prototype);
};

๋งˆ๋ฒ•์ด ์ผ์–ด๋‚˜๋Š” ๊ณณ์ด ๋ฐ”๋กœ ์ด ๊ณณ์ด์•ผ!
ํ”„๋กœํ† ํƒ€์ž…์„ ๋ณต์ œํ•จ์œผ๋กœ์จ function์„ ์ƒˆ๋กœ์šด ํด๋ž˜์Šค๋กœ ์ด์ „ํ•œ๋‹ค.

๊ทธ๋ž˜์„œ ์ฒซ ๋ฒˆ์งธ ํด๋ž˜์Šค๊ฐ€ ๋  ๋‘ ๋ฒˆ์งธ ํด๋ž˜์Šค๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ์ด ์ฝ”๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ๋งŒ ํ•œ๋‹ค.

var ClassB = function() {
    this.name = "class B";
    this.surname = "I'm the child";
}

inheritsFrom(ClassB, ClassA);

ClassB๊ฐ€ ClassA์˜ print๊ธฐ๋Šฅ ์ƒ์†๋ฐ›์•˜๋‹ค.

var b = new ClassB();
b.print();

๊ฒฐ๊ณผ,

class B

ClassB์˜ ์ธ์‡„ ๊ธฐ๋Šฅ๋„ ๋ฌด์‹œํ•  ์ˆ˜ ์žˆ๋‹ค.

ClassB.prototype.print = function() {
    ClassA.prototype.print.call(this);
    console.log(this.surname);
}

๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์„ ๊ฒƒ์ด๋‹ค

class B 
Iโ€™m the child

์—ฌ๊ธฐ์„œ print function์„ ์–ป๊ธฐ ์œ„ํ•ด ClassA.prototype์œผ๋กœ callํ•˜๋Š” ๊ฒƒ์ด๋‹ค.
๊ทธ๋Ÿฐ ๋‹ค์Œ call function ๋•๋ถ„์— ํ˜„์žฌ Object์˜ ๊ธฐ๋ณธ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค(this).

ClassC๋ฅผ ๋งŒ๋“œ๋Š”๊ฒŒ ๋ช…ํ™•ํ•ด์กŒ๋‹ค.

var ClassC = function () {
    this.name = "class C";
    this.surname = "I'm the grandchild";
}

inheritsFrom(ClassC, ClassB);

ClassC.prototype.foo = function() {
    // Do some funky stuff here...
}

ClassC.prototype.print = function () {
    ClassB.prototype.print.call(this);
    console.log("Sounds like this is working!");
}

var c = new ClassC();
c.print();

๊ฒฐ๊ณผ

class C 
Iโ€™m the grandchild 
Sounds like this is working!