2014-05-13 1 views
0

내가 아주 간단한 JS 응용 프로그램을 서면으로 객관적 접근 방법을 적용하려고하지만 바로 그것을 얻을 수가 어차피 ...목적 자바 스크립트

이 예에서 (테이블에서 데이터를 조작하는 몇 가지 기능이 있습니다 - 강조 행 링크를 클릭 한 후 임의의 색상으로 표시). 이 예에서 JSFiddle

var MainFun = function() {} 

MainFun.prototype.highlight = function(value) { 
     $(".conversationid") 
      .filter(function() { 
       return $(this).html() == value; 
      }) 
      .css('background', 'transparent') 
      .parent() 
      .css('background', getRandomColor()); 
} 


function getRandomColor() { 
    return '#' + randHex() + "" + randHex() + "" + randHex(); 
} 

function randHex() { 
    return (Math.floor(Math.random() * 106) + 150).toString(16); 
} 

var f = new MainFun(); 

<table> 
    <tr> 
     <td class="message">message1</td> 
     <td class="conversationid">123</td> 
     <td class="details"><a href="#"onclick="f.highlight('123');">click me</a></td>    
    </tr> 
    <tr> 
     <td class="message">message2</td> 
     <td class="conversationid">456</td> 
     <td class="details"><a href="#"onclick="f.highlight('456');">click me</a></td>    
    </tr> 
    <tr> 
     <td class="message">message3</td> 
     <td class="conversationid">123</td> 
     <td class="details"><a href="#"onclick="f.highlight('123');">click me</a></td>    
    </tr> 
    <tr> 
     <td class="message">message4</td> 
     <td class="conversationid">456</td> 
     <td class="details"><a href="#"onclick="f.highlight('456');">click me</a></td>    
    </tr> 

에 일례가있다

, MainFun 모든 기능을 포함해야 메인 objhect (하이라이트 getRandomColor 등)

필자는 prototype을 사용하여 강조 기능을 사용하도록 만들었지 만 다른 기능과 동일하게하려고하면 "f undefined"라는 오류가 발생합니다. 어떻게 할 수 있는지 제안 해 주시겠습니까? JS에서의 객관적인 접근 방식은 다른 언어 들과는 상당히 다른 것 같습니다. 어떤 도움을 주셔서 감사합니다!

+1

당신이 '객관적'접근 방식에 의해 무엇을 의미합니까? '객체 지향'을 의미합니까? –

+2

작동하지 않는 기능 - 작동하지 않는 기능의 예를 들어 주시겠습니까? –

+0

예, 프로토 타입을 사용하여 객체 지향 접근법을 의미합니다 ...이 코드를 완전히 객체 지향적으로 재 작성하려고합니다 ... – Smajl

답변

2

highlight 기능을 사용했던 것처럼 할 수 있습니다. 그리고 this으로 (또한 하이라이트 기능에서) 다른 프로토 타입 함수를 호출하기 때문에 JQuery와에

var that = this; 

그건 : jsfiddle

주 라인 :

MainFun.prototype.getRandomColor = function() { 
    return '#' + this.randHex() + "" + this.randHex() + "" + this.randHex(); 
} 

MainFun.prototype.randHex = function() { 
    return (Math.floor(Math.random() * 106) + 150).toString(16); 
} 

나는 바이올린을 업데이트했습니다 폐쇄 범위 this의 의미가 변경됩니다.

+0

고마워, 내가 찾고 있었던 것이었다! – Smajl

+0

이 예제에서는'getRandomColor'가 클로저에서 호출되지 않았기 때문에'var that = this;'는 필요하지 않습니다. 그러나 당신은 미래를 위해 당신의 머리 속에 유지할 수 있습니다.) – bitWorking

+0

각 기능을 수퍼 메인 "클래스"에 넣는 것은 "객체 지향 접근법"과 아무 관련이 없습니다. 그러한 간단한 예제를 위해 유용한 객체 지향 솔루션을 찾는 것은 어렵습니다. – hansmaad

0

저는 이것이 객체 지향 디자인을 만드는 합리적인 예가 아니라고 생각합니다. 간단하고 간단한 솔루션이 있어야합니다.

어쨌든 ... 각 기능을 슈퍼 메인 "클래스"에 넣는 것 MainFun은 "객체 지향 접근 방식"과 아무 관련이 없습니다. 이전과 같은 디자인입니다. OOP로 시작하기를 원한다면 책임에 대해 생각하고 그들을위한 객체를 만들어야합니다. 이 예에서는 MainFunc에서 ColorPicker을 추출 할 수 있습니다. 그리고 RandomColorPicker은 임의의 16 진수를 반환하는 함수 인 임의의 엔진에 대한 종속성을 가질 수 있습니다.

JSFiddle

var Main = function(colorPicker) { 
    var that = this; 
    this.colorPicker = colorPicker; 

    this.highlight = function(value) { 
     $(".conversationid").filter(function() { 
      return $(this).html() == value; 
     }) 
     .css('background', 'transparent') 
     .parent() 
     .css('background', that.colorPicker.pickColor()); 
    }; 
}; 

var RandomColorPicker = function(randomEngine) { 
    this.rand = randomEngine; 
}; 

RandomColorPicker.prototype.pickColor = function() { 
    return '#' + this.rand() + "" + this.rand() + "" + this.rand(); 
}; 

var randHex = function() { 
    return (Math.floor(Math.random() * 106) + 150).toString(16); 
}; 

var f = new Main(new RandomColorPicker(randHex)); 
+0

예제가 객체 지향 디자인을 보여주는 것이 가장 좋지 않습니다. 다중 인스턴스가 필요 없기 때문에 객체 리터럴 방식이 더 적합합니다. 그러나 당신의'thishighlight'는 정말 나쁜 디자인입니다. 새 인스턴스를 만들 때마다 복사되는 생성자 함수 내부에 중첩 된 함수입니다. [here] (http://code.tutsplus.com/tutorials/stop-nesting-functions-but-not-all-of-them--net-22315)에 대해 읽어보십시오. – bitWorking

+0

@bitWorking 항상 하나의 인스턴스 만 있기 때문에 중요하지 않습니다. – hansmaad

+0

죄송합니다.하지만 이것은 잘못된 디자인을 정당화하기위한 논의가 아닙니다. 라이브러리를 작성하는 경우 다른 사람이 라이브러리를 어떻게 사용하는지 알 수 없습니다. – bitWorking