일반적으로 데이터를 저장하기 위해 JavaScript의 객체를 사용하지만 이벤트 수신기는 보조 포인터가 이러한 객체를 검색 할 수 없도록합니다.JavaScript의 이벤트 콜백에서 객체를 검색하는 가장 좋은 방법은 무엇입니까
이벤트 콜백에서 객체 포인터를 검색하는 가장 좋은 방법은 무엇입니까? (제 3의 라이브러리는 만족하지 않고)
예 : 현재
function MyClass()
{
this.number = Math.random();
this.button = document.createElement('div');
this.button.appendChild(document.createTextNode('Show number'));
document.body.appendChild(this.button);
// THIS FOLLOWING LINE REQUIRE CHANGES
this.button.addEventListener('click', MyClass.prototype.listener);
}
MyClass.prototype.listener = function (e)
{
// HERE, "THIS" DO NOT POINT TO MY OBJECT
alert(this.number);
}
testMyClass1 = new MyClass();
testMyClass2 = new MyClass();
, 나는 포인터를 저장하는 정적 배열을 사용하지만 유지하기 어렵다 :
//New constructor, first try
function MyClass()
{
this.number = Math.random();
this.button = document.createElement('div');
this.button.appendChild(document.createTextNode('Show number'));
document.body.appendChild(this.button);
if (undefined===MyClass.prototype.register) MyClass.prototype.register = [];
this.id = MyClass.prototype.register.length;
MyClass.prototype.register.push(this);
this.callback = new Function('e',
'var self = MyClass.prototype.register[' + this.id + '];'+
'MyClass.prototype.listener.call(self, e);'
);
this.button.addEventListener('click', this.callback);
}
참고 :
- 전이 함수의 생성을 피하기 위해 생성자 내에 클래스 함수를 정의하고 싶지 않습니다. 많은 양의 메모리를 필요로합니다. 어쨌든 내 솔루션은 여전히 작은 기능을 저장합니다. ES5를 사용
너무 빨리 나를 위해! –