2014-01-14 3 views
2

Possible duplicate이 나에게 도움이되지 않았다. 나는 비슷한 질문 때문에 인터뷰에서 실패했다.객체를 모듈 패턴과 결합 할 때 내가 뭘 잘못하고 있니?

module patterninheritance을 사용하여 관리자의 선배이자 할아버지 인 사람 Object을 만드는 것이 좋습니다.

내 코드처럼 보이는 관리자 -> Teacher-> 사람처럼 뭔가 (My Plunk) :

var person = new APP.Person('Aria Stark','22323'); 

이 오류는 다음과 같습니다

(function(undef) 
{ 
    /**Waiting till document is ready before applying next functions*/ 
    $(document).ready(function(){ 

     var person = new APP.Person('Aria Stark','223232'); 
     document.write(person.getDetails()); 
    })(); 

    var APP = {}; 

    APP.Person =(function() { 

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

     Person.prototype.getDetails = function() { 
      return " name: " + this.name + " ID: " + this.ID; 
     }; 

     return Person; 
    }); 

    APP.Teacher =(function() { 

     function Teacher(name, ID, salary, hatColor) { 
      APP.Person.call(this, name, ID); 
      this.salary = salary; 
      this.hatColor = hatColor; 
     } 

     Teacher.prototype = new APP.Person(); 

     Teacher.prototype.getDetails = function() { 
      return APP.Person.call(this) + " Salary: " + this.salary + " Hat: " + this.hatColor; 
     }; 

     return Teacher; 
    }); 


    APP.Manager =(function() { 

     function Manager(name, ID, salary, hatColor, car) { 
      APP.Teacher.call(this, name, ID, salary, hatColor); 
      this.car = car; 
     } 

     Manager.prototype = new APP.Teacher(); 

     Manager.prototype.getDetails = function() { 
      return APP.Teacher.call(this) + " Car: " + this.car; 
     }; 

     return Manager; 
    }); 


})(); 

나는 첫 번째 줄에 오류가 : Uncaught TypeError: object is not a function

누군가 나를 도와 줄 수 있습니까? 또한이 코드의 다른 개선 사항에 대해서도 열려 있습니다.

답변

3

이 생성 (과) 호출 방법이다 self-executing function or IIFE :

(function() {})(); 

간단히 함수를 호출하지 않습니다 (function() {})를 작성, 실제로이 경우에 실제 영향을주지 않습니다. 방법이 APP.Person 일 때이라고하는 다른 함수 (Person의 생성자) 을 반환하는 함수가됩니다. 이는 new과 잘 작동하지 않습니다. 이벤트가 트리거 할 때

또한, documentready을 위해, 당신은이 호출됩니다 단지 매개 변수로 function 전달의 .ready 호출의 결과를 실행하지 않으 :

$(document).ready(function(){ 
}); //removed() from here 

Plunk with these changes

+0

감사합니다,하지만이 답변이 새로운 문제로 연결 : http://plnkr.co/edit/fyg4JDBQp9DSzvI6pvOx?p=preview, 교사용 개체를 만들려고 할 때 – Canttouchit

+0

@Canttouchit 내가 살펴 보겠습니다. 한편'document.write'는'console.log'라는 것을 잊어 버리십시오. 매우 유용합니다. – kapa

+0

네, 깜빡 :'return APP.Person.prototype.getDetails.call (this)' – Canttouchit

1

귀하의 모든 객체는 다음과 같이 선언된다 : 그것은 조금 이상한하지만, 그 자체가 잘못되지

APP.X=(function() { 
    function Y() {} 
    Y.prototype.method= function() {}; 
    return Y; 
}); 

. 원하는 것은 다음과 같습니다.

APP.X=(function() { 
    function X() {} 
    X.prototype.method= function() {}; 
    return X; 
})(); // actually call the anonymous function you used to encapsulate variables 

그런데 왜 IIFE로 귀찮게합니까? 당신은뿐만 아니라이 작업을 수행 할 수 있습니다

APP.X = function() {} 
X.prototype.method= function() {}; 

을 캡슐화 절대적으로 아무것도 제공하지 않습니다, 당신은 외부 범위에서 숨어 개인 아무것도 없다.


또한 내 게시물은 StackOverflow보다 CodeReview에 더 적합 할 수 있지만 상속 모델에 중요한 문제가 있습니다. Teacher.prototype은 매개 변수없이 작성된 Person의 인스턴스입니다. 매우 제한적인 상황에서만 안전합니다.

Teacher = function(){ 
    Person.call(this /*, person parameters*/); 
} 
Teacher.prototype = Object.create(Person.prototype); 

많은 좋은 답변 SO이 특정 문제를 다루는에있다, here 날로부터 하나입니다

더 나은 모델이 하나가 될 것입니다.

+0

그가 IIFE에서 얻은 유일한 것은 가독성입니다. 함께 속하는 것들 (프로토 타입을위한 생성자와 메소드)은 그룹화되어 있습니다. 시각적으로 더 이해하기 쉬워진다. 하지만 물론 +1. – kapa

0

이러한 것들을 생성하기 위해 jQuery가 필요하지 않습니다. 글쎄, 난이 켜져 있지 아주 좋은 노광기를 가지고,하지만 난 당신이 알고 싶은 것을 보여 주려고 :

// Creating Person Class 
var Person = function(name, id){ 
    this.name = name; 
    this.id = id; 
}; 

Person.prototype.getInfo = function(){ 
    return "name: " + this.name + ", id: " + this.id; 
}; 

// Instance of Person 
var x = new Person("Ashish", 1); 
x.getInfo(); 

// Creating Teacher Class 
var Teacher = function(name, id, salary, hatColor){ 
    Person.call(this, name, id); 
    this.salary = salary; 
    this.hatColor = hatColor; 
}; 

// Inheriting Persons methods 
Teacher.prototype = new Person(); 

// Adding new method to it 
Teacher.prototype.getFullDetails = function(){ 
    return this.getInfo() + ", salary: " + this.salary + ", Hatcolor: " + this.hatColor; 
} 

// Instance of Teacher Class 
var teacher = new Teacher("John", 2, 15000, "red"); 
teacher.getInfo(); //output: "name: John, id: 2" 
teacher.getFullDetails(); // output : "name: John, id: 2, salary: 15000, Hatcolor: red" 
console.log(teacher.salary); // output : 15000 

을 그래서, 당신이 볼 수 위 : - Person 클래스가이 속성과 하나의 방법으로 만들어집니다 . - 그런 다음 Teacher 클래스를 만들고이 클래스에 Person 클래스의 메서드를 상속합니다. - 그런 다음 getFullDetails()이라는 메서드를 추가하여 Person 클래스의 메서드에 액세스합니다.

그리고 이것은 당신이 DOM.ready에서하고있는 것입니다 : 당신의 예에서

alert(x.getInfo()); // in my example: 

: 대답에 대한

var APP = {}; 
APP.Person = function Person(name, ID) { 
    this.name = name; 
    this.ID = ID; 
} 

APP.Person.prototype.getDetails = function() { 
    return " name: " + this.name + " ID: " + this.ID; 
}; 

var person = new APP.Person('Aria Stark', '223232'); 
alert(person.getDetails()); 
+0

그는 단지 jQuery를 사용하여 documentready 이벤트를 잡았습니다. – kapa