2010-12-03 4 views
1

가 주어 자신을 참조하는? 객체 내부에서 사물을 참조해야하므로 외부 독립형 함수가 필요하지 않습니다.자바 스크립트, 디자인 기능은

예를 들어 함수는 ganttChart 객체의 특정 인스턴스에 정의 된 variable1/2/3을 참조 할 수 있습니다 (여러 차트 객체를 가질 수 있음).

희망이 맞습니다! EG :

function ganttChart(gContainerID) { 

    this.variable1 = "lol"; 
    this.variable2 = "hai dere"; 
    this.variable3 = "cometishian"; 

.... 
    this.gContainer.innerHTML += "<div id=\"gBar" + i + 
      "\" class=\"gBar\" onmousedown=\"gInitBarDrag(this)\">Hello</div>"; 
.... 

    gInitBarDrag = function(thisGanttObject) 
    { 
     alert(thisGanttObject.variable2); 
     // This line wont work because it doesn't know what ganttChart to reference! 
    } 

} 
+0

@Tom 'this'값은 무엇을 의미합니까? –

+0

ganttchart 개체입니다. –

+0

@Tom "granttChart class"는 무엇을 의미합니까? granattChart는 함수이며 JavaScript에 클래스가 없습니다. –

답변

2
function gnattChart(gContainerID) { 
    var div = document.createElement('div'); 
    div.id = 'gBar'; 
    div.className = 'gBar'; 

    //If you want to reference properties from the gnattChart object... 
    //Use `self` where you'd normally use `this` in the handler function 
    var self = this; 

    div.onmousedown = function() { 
    //contents of gInitBarDrag here... 
    }; 

    //If you want the container to be emptied... 
    this.gContainer.innerHTML = ''; 

    this.gContainer.appendChild(div); 
} 
+0

+1이 올바른 시도하고 구현할 것입니다 –

+0

+1 그게해야합니다. (비록 라이브러리를 사용하여 이벤트 핸들러를 부착하는 것을 선호하지만) –

+0

@ ime Vidas - 자바에 대해 이야기 할 때 접하는 것은 쉽지 않습니다. 그냥 단순하게 유지하려고합니다. 운좋게도'onevent' DOMNode 속성을 사용하는 것이 100 % 크로스 브라우저이고 적어도 이상적인 인라인 이벤트 속성보다 훨씬 더 좋은 순서입니다. – MooGoo

0
this.gContainer.innerHTML += "<div id=\"gBar" + i + "\" class=\"gBar\" onmousedown=\"function(){ alert('here'); }\">Hello</div>"; 

있지만, 인라인 함수는 일반적으로 눈살을 찌푸리게한다.

+0

내 눈이 막 죽었습니다. 추한,하지만 정확함 +1. – Stephen

+0

미안하지만 내 질문 사항을 놓치지 마라. 함수는 기본 ganttChart 객체 내의 변수에 액세스 할 수 있어야한다. –

-1
var gInitBarDrag = function(){ 
    ///function body here 
}; 

function ganttChart(gContainerID) { 
.... 

    this.gContainer.innerHTML += "<div id=\"gBar" + i + "\" class=\"gBar\" onmousedown=\"gInitBarDrag(this)\">Hello</div>"; 
.... 


} 
+0

ganttChart 객체에 포함 된 변수를 참조 할 수 있습니까? –

+0

No ...'gInitBarDrag'라고하는 전역 함수를 찾고 아무 것도 찾지 않고 예외 번호 – MooGoo

+0

을 복사하여 붙여 넣기 실수를 범합니다. 그것을 고정 –

0

OK, 나는 그것을 테스트하고 prototypejs를 사용하지 않고 대답한다,하지만 난 당신이 운동을 자신의 기능을 당신이 JS 프레임 워크를 사용하지 않을 수 있는지 확신합니다.

먼저 document.createElement를 사용하는 대신에, 이런 식으로 뭔가를 HTML을 주입하여 사업부를 만들 것입니다 :

다음
var d = document.createElement("div"); 
// Set your div properly. 

당신은 당신의 새로운 사업부 (변수 D를 넣어되는 document.appendChild을 사용해야합니다)를 귀하의 페이지에 추가하십시오. "어려운"부분 : 마우스 다운 이벤트를 듣고 그에 따라 행동하십시오. Event.observe (prototypejs) 및 bind (prototypejs)를 사용하여 객체를 수신기에 바인딩하므로 변수 (this.variable1, variable2 등)를 사용할 수 있습니다. 바인딩과 JS 프레임 워크없이 다소 쉽게 구현 될 수 관찰 :

function ganttChart(gContainerID) { 

this.variable1 = "lol"; 
this.variable2 = "hai dere"; 
this.variable3 = "cometishian"; 

// Create Element part (createElement, appendChild, etc). 
var d = document.createElement("div"); 
// continue from here. 


this.gInitBarDrag = function() 
{ 
    alert(this.variable2); 
}; 

$(d).observe("mousedown", this.gInitBarDrag.bind(this)); 

} 

일부 노트 :

은 다음과 같이 다소 코드를 제공합니다. 이 코드는 테스트되지 않았습니다.

0

당신은 다음 this 객체에 점 객체의 속성으로 함수를 정의하는 경우 :

var에 인 myObject = {foo는 : 사실, 막대 : 함수() {경우 (this.foo) {doStuff (); }};

this이 개체를 반환하는 생성자 함수에 사용되는 경우 this은 반환되는 새 개체에 바인딩됩니다. 귀하가 게시 한 코드에 this을 사용하는 방식으로, this은 자바 스코어의 잘못된 부분 중 하나 인 전역 범위를 가리 킵니다.

그래서, 여기에 내가이 접근 할 방법은 다음과 같습니다
function GanttChart(gContainerID) { 
    var chart = { 
    variable1: "lol", 
    variable2: "hai dere", 
    variable3: "cometishian", 
    containerId: gContainerID, 
    gInitBarDrag: function(){ 
     alert(this.variable2); 
     } 
    } 
    return chart; 
} 
myChart = new GanttChart("chart1"); 
document.getElementById(myChart.containerId).innerHTML += "<div id=\"gBar" + i + "\" class=\"gBar\" onmousedown=\"myChart.gInitBarDrag();\">Hello</div>"; 

내가 때문에 관례 적으로 대문자로하는 간트 차트 기능을 변경, 객체를 반환 생성자 함수는 대문자로한다.

관련 문제