간단한 HTML 및 Javascript 코드가 있습니다.
<span id="test">Hej</span>
function Hello(el)
{
var el = document.getElementById('test');
this.test = function(fun)
{
el.addEventListener('click', function(e)
{
fun(e);
}, false);
}
}
var hello = new Hello;
hello.test(function()
{
console.log(this);
});
console.log ()에서 "this"를 사용하고 싶지만 hello의 인스턴스를 참조하고 싶습니다. Hello의 정의를 어떻게 변경해야합니까?
을 사용 하면 원하는대로 Function#call
바인딩 할 수 있습니다 this
.
function Hello(el)
{
var el = document.getElementById('test');
var that = this;
this.test = function(fun)
{
el.addEventListener('click', function(e)
{
fun.call(that, e);
}, false);
}
}
이 jsfiddle을 참조하십시오 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다