JS의 원형 체인(메소드 상속)

1214 단어
Document

    //  


    // Person  
    function Person(name,age){
        this.name = name;
        this.age = age;
    }

    Person.prototype.run = function () { 
        console.log(`${this.name} 。`);
    }

    Person.prototype.sayHi = function () { 
        console.log(`${this.name}  SayHi`);
    }

    // Student  
    function Student(name,age,number){
        this.name = name;
        this.age = age;
        this.number = number;
    }
    
    //   Student   new Person();
    //  :  Student   Person  
    ****Student.prototype = new Person();****
    //   constructor  
    **Student.prototype.constructor = Student;**

    //  , 
    Student.prototype.code = function(){
        console.log(`${this.name}  Coding  `);
    }

    // new Person() === Student.prototype // ??? false, 

    const s1 = new Student(' ', 19, ' 666');

    console.log(Person.prototype.constructor);  // Person
    console.log(Student.prototype.constructor); // Student

    console.log(s1.__proto__ === Student.prototype);    // true

    s1.sayHi();

    console.log(Student.prototype); // ?? Person {name: undefined, age: undefined, constructor: ƒ, code: ƒ}


좋은 웹페이지 즐겨찾기