// 확장 된 기본 클래스 코드 (압축되지 않은 코드가 필요한 경우 게시 해 드리겠습니다.) function Class() {} Class.prototype.construct = function() {}; Class.extend = function (c) { var e = function() {arguments [0]! == Class & & this.construct.apply (this, arguments)}, d = new this (Class), f = this.prototype; for (var e in c) b. $ = f; d [e] = b} a.prototype = d; a.extend = this.extend; return a};메소드가 속한 인스턴스를 어떻게 찾을 수 있습니까?
// custom event class
var Event = Class.extend({
handlers: [],
// stores the event handler
subscribe: function(handler, thisObj) {
this.handlers.push([handler, thisObj]);
},
// calls the event handlers
fire: function() {
for(i in this.handlers) {
var handler = this.handlers[i];
handler[0].apply(handler[1]);
}
}
});
var Class2 = Class.extend({
myEvent: new Event(), // the event
test: function() { // fires the event
this.myEvent.fire(this);
}
});
var Class3 = Class.extend({
construct: function(model) {
this.name = "abc";
model.myEvent.subscribe(this.handler, this); // subscribe to the event
},
handler: function() {
alert(this.name); // alerts 'abc'
}
});
var instance1 = new Class2();
var instance2 = new Class3(instance1);
instance1.test();
'수신'방법에 새로운 인수 ('thisObj')를 추가하여 '이'는 좋은 작업을 할 수있는 이벤트 핸들러 코드를 만들 수있는 유일한 방법은? 이 작업을 수행하는 더 좋은 방법이 있습니까?
파이어 폭스에서이 코드를 실행할 때 나는 self.handler가 함수가 아니다 .. 나는이 클로저에 대해 더 많이 읽고 .. bind의 프로토 타입 구현을 보라. jQuery는 또한 내가 생각하기에 $ .proxy를 가지고있다. 같은 일을하지만, JavaScript 라이브러리와 독립적이어야하는 작은 프로젝트를 진행하고 있습니다. 어쨌든 감사합니다! – silviubogan
즉시 실행되는 익명의 함수는 전역 객체를 가리키는'this' 값을 항상 갖습니다. 즉,'(function() {return this === window;})(); // true' 인 경우, 그 함수가 필요 없으므로, 둘러싼 함수 (construct)에서'var self = this;'를 지정하고 반환하는 것과 같은 간단한 익명 함수를 사용하여'self .handler();'. – CMS
'this'가 전역 개체를 참조하는 익명 함수에 대한 첫 번째 부분을 알지 못했습니다. 그거 알아두면 좋을거야. 감사! –