2017-02-03 10 views
0

계시 모듈 패턴을 상속과 함께 사용하려고합니다. 나는 잘 작동하는 것 같지만, "__proto__"을 사용한다. 나는 그것을 비추천으로 간주한다. "__proto__"를 사용하여 상속을 만드는 것이 더 나은가요?__proto__를 사용하는 것과 동일합니까?

var Person = (function() { 
    var _name; 
    var api = { 
     init: init, 
     getName: getName 
    } 
    return api; 

    function init(name) { 
     _name = name; 
    } 

    function getName() { 
     return _name; 
    } 
}()) 

var Teacher = (function() { 
    var _subject = "Math"; 
    var api = { 
     getSubject: getSubject, 
     say: say 
    } 
    api.__proto__ = Person; 
    return api; 

    function getSubject() { 
     return _subject; 
    } 

    function say() { 
     console.log("I am " + this.getName() + " and I teach " + _subject) 
    } 
}()); 

Teacher.init("Bob"); 
Teacher.say() // I am Bob and I teach math 

https://plnkr.co/edit/XbGx38oCyvRn79xnn2FR?p=preview

+1

내가 볼 수 없습니다 당신은 창조 할 때 그것을 설정합니다. –

답변

4

직접 해당 - 아직 프로토 타입, 나쁜 생각을 설정 - Object.setPrototypeOf입니다 :

Object.setPrototypeOf(api, Person); 

다음 Object.create하고있는 프로토 타입을 기반으로 객체를 생성하는 일반적인 방법 여기에 속성을 추가해도 괜찮습니다.

var api = Object.create(Person); 
api.getSubject = getSubject; 
api.say = say; 

그러나 이상적으로 당신은 그냥 사용하는 것이 생성자 : ES6없이

class Person { 
    constructor(name) { 
     this._name = name; 
    } 

    getName() { 
     return this._name; 
    } 
} 

class Teacher extends Person { 
    constructor(name) { 
     super(name); 
     this._subject = 'Math'; 
    } 

    getSubject() { 
     return this._subject; 
    } 

    say() { 
     console.log(`I am ${this.getName()} and I teach ${this.getSubject()}`); 
    } 
} 

var teacher = new Teacher('Bob'); 
teacher.say() // I am Bob and I teach math 

: 당신은`Object.create`이 있습니다 때 객체를 생성 한 후 프로토 타입 체인을 설정해야하는 이유

function Person(name) { 
    this._name = name; 
} 

Person.prototype.getName = function() { 
    return this._name; 
}; 

function Teacher(name) { 
    Person.call(this, name); 
    this._subject = 'Math'; 
} 

Teacher.prototype = Object.create(Person.prototype); 

Teacher.prototype.getSubject = function() { 
    return this._subject; 
}; 

Teacher.prototype.say = function() { 
    console.log('I am ' + this.getName() + ' and I teach ' + this.getSubject()); 
}; 

var teacher = new Teacher('Bob'); 
teacher.say(); // I am Bob and I teach math 
+0

JS6은 불행히도 옵션은 아니지만 Object.create()는 jquery의 도움을 받아 트릭을 수행했다. $ .extend (api, Object.create (Person)); – Skyler

+0

@Skyler : 왜 거기에'$ .extend'가 필요한가요? 어쨌든 생성자를 사용하기 위해 ES6 클래스를 사용할 필요는 없습니다. 편집을 참조하십시오. – Ryan

+0

저는 코드 블록의 상단에있는 api 객체에 내 퍼블릭 메소드를 정의하고 싶습니다. 그래서 $ .extend를 사용하여 기본 객체와 결합합니다. – Skyler