2012-07-23 3 views
2

바인드를 사용하여 'this'의 범위를 변경하여 클릭 기능 내에서 'this'를 사용하여 generateContent 함수를 참조 할 수 있습니다. 불행히도 이것은 this.id가 더 이상 'this'의 범위가 변경됨에 따라 작동하지 않는다는 것을 의미합니다.바인드 프로토 타입을 사용하여 'this'의 범위 변경

이 경우, 클릭 된 버튼의 id를 잡아 수있는 가장 좋은 방법은 무엇입니까 :

function help(doc) { 

    buttons: function() { 

     $('.add-btn').click(function() { 

     this.generateContent(this.id)); 

     }.bind(this)); 

    }, 

    generateContent: function (id){ 

    } 

} 

// This function binds a function to an object's scope. 
Function.prototype.bind = function(scope) { 
    var _function = this; 
    return function() { 
     return _function.apply(scope, arguments); 
    } 
} 

답변

5

당신은 jQuery를 태그하지 않았다하지만, jQuery를 그래서 난 jQuery를 가정 것 같은 코드가 꽥꽥.

jQuery를이 event.currentTarget 제공 :

$('.add-btn').click(function(e) { 
    this.generateContent(e.currentTarget.id) ; 
}.bind(this)); 

Btw는 Function.prototype.bind가 기본적으로 존재하는, 당신은 기본 버전은 사용할 수있는 경우에 덮어 쓰기를 원하지 않는다. jQuery는 $.proxy도 제공하므로 어떤 경우에도 필요하지 않습니다.

See demo

+0

대단히 감사합니다. 정확하게 알고 싶었습니다. Jquery 태그를 추가했습니다. – Lishamatish

관련 문제