2015-01-06 2 views
2

선택자가없는 jQuery 플러그인에서 작업하고 있습니다. 초기화 할 때 함수가있는 객체를 인스턴스화합니다. 이 함수에서는 클로저를 사용해야합니다. 이 클로저에서는 초기 객체 함수를 호출하고 싶습니다.클로저에서 javascript 클래스 함수를 호출하는 방법

더 명확히하기 위해 다음은 단순화 된 코드 버전입니다.

HTML

<script src="/path/to/jquery/2.1.1/jquery.min.js"></script> 
<script src="/path/to/my/script/myeditor.js"></script> 

<div class="editable">Div1</div> 
<div class="editable">Div2</div> 

<script> 
    $.myeditor({ 
     option1: 'a', 
     option2: 'b' 
    }); 
</script> 

myeditor.js

function ($) { 

var MyEditor = function (options) 
{ 
    this.$options = $.extend(true, {}, $.myeditor.defaults, options); 
    this.init(); 
}; 

$.myeditor = function (options = {}) 
{ 
    return new MyEditor(options); 
}; 

$.flyeditor.defaults = { 
    option1: '1', 
    option2: '2' 
}; 

MyEditor.prototype.notify = function(message = '') 
{ 
    console.log(message); 
}; 

MyEditor.prototype.init = function() 
{ 
    // Do stuff 
    $('.editables').each(function() { 
     $this = $(this); 

     // Here comes the error 
     notify($this.html()); 
    }); 
}; 

}(jQuery); 

문제는 notify(this.html());ReferenceError: notify is not defined

가 어떻게이 방법을 통지 도달 할 수있는 오류를 발생시킵니다이다?

+1

'MyEditor.prototype.notify = 기능 (메시지 = '') {'유효한 자바 스크립트, 당신은 전처리를 사용하지 않습니까? –

답변

6

this을 클로저의 별도 로컬 변수에 할당 할 수 있습니다. 함수가 MyEditor의 프로토 타입에 부착되어 있기 때문에 당신은 thiseach 내부 사용자의 MyEditor 객체에 더 이상 점, 그것은 또한 .editables

의 각을 가리 킵니다 때문에, 당신은 아마 this.notify()를 호출하는 의미 있다고 할 필요가

MyEditor.prototype.init = function() 
{ 
    // Do stuff 
    var that = this; // <-- now we can reach this inside function. 
    $('.editables').each(function() { 
     $this = $(this); 

     // Here comes the error 
     // You can't use notify, that function is not defined 
     // You can't use this.notify because this points to something else (the node) 
     // inside the function in each 
     that.notify($this.html()); 
    }); 
}; 
+1

이것은 실제로 OP가 요구하는 것입니다. 그는 프로토 타입에있는 것처럼 알림에 도달 할 수 없으므로 '이'가 필요하지만 폐쇄 상태에 있기 때문에 내부에서 액세스하려면 클로저 외부에있는 항목을 할당해야합니다. – japrescott

+0

@Juhana'this'는'each '의 내부에서 다른 문맥입니다 – charlietfl

+0

나는 이것을 두 번 되돌려 보았습니다. (정말로 말장난이 아니 었습니다.) upvote back. –

0
MyEditor.prototype.init = function() 
{ 
// Do stuff 
var self = this; 
$('.editables').each(function() { 
    $this = $(this); 

    // Here comes the error 
    self.notify($this.html()); 
}); 
}; 
+0

어떻게 작동하는지에 대한 설명? –

+2

이것은 [Jimmy] (http://stackoverflow.com/a/27800676/227299) 이미 언급 한 것과 같습니다. –

관련 문제