5

質問のタイトルを正しく表現したかどうかはわかりません。明確にするために以下を検討してください...

(function() {
    var foo = {
        bar: function() {
            // Is it possible to reference 'this' as the
            // initializing 'object' aka 'e' and not 'foo' ?
            // The easy part, currently because 'this' refers to 'foo',
            // is returning 'this' aka 'foo' so that chaining can occur
            return this;
        },
        other: function() {
            return this;
        }
    };
    Event.prototype.foo = foo; 
}());

// usage
document.onmousemove = function(e) {
    e.foo.bar().other();
};

のメソッド/小道具this内にアクセスするfoothisはどうすればよいですか?objectefoo


私が思いついた最高のものはこれです

(function() {
    var foo = function() {
        var _foo = this.foo;
        _foo._this = this; //recursive reference that I am VERY worried about
        return _foo;
    };
    foo.bar = function() {
        var _this = this._this; //_this refers to initial 'object', 'e'
        return this; //return 'foo' aka 'this' for function chaining
    };
    foo.other = function() {
        var _this = this._this;
        return this;
    };
    Event.prototype.foo = foo; 
}());

// usage
document.onmousemove = function(e) {
    e.foo().bar().other();
};

私が現在持っているものは機能しますが、いくつかのことが心配です... 1.への割り当て

の再帰参照 と2.eへ の割り当ての冗長性。特に mousemove イベントのようなものに関して。e.foo._this



ee.foo._thisthisefoo

ここでjsFiddle


また、私はこのようなことを避けようとしています...

document.onmousemove = function(e) {
    e.foo.bar.call(e);
};

お時間をいただきありがとうございます。

4

3 に答える 3

2

あなたが持っているものに微妙な変更を加えることで、物事をよりシンプルにすることができます:

(function() {
    var foo = function() {
      this.foo.event = this;
      return this.foo;
    };
    foo.bar = function() {
      /// the event can be found in this.event
      return this;
    };
    foo.other = function() {
      /// the event can be found in this.event
      return this;
    };
    Event.prototype.foo = foo;
}());

// usage
document.onmousedown = function(e) {
    e.foo().bar().other();
};

ただし、これは共有オブジェクトに変更を加えています。代わりにの新しいインスタンスを返すfooように書き直し、他のメソッドをプロトタイプに移動することをお勧めします。e.foo()foofoo's

(function() {
    var foo = function(event) {
      this.event = event;
    };
    foo.prototype.bar = function() {
      /// the event can be found in this.event
      return this;
    };
    foo.prototype.other = function() {
      /// the event can be found in this.event
      return this;
    };
    Event.prototype.foo = function() {
      return new foo(this);
    };
}());

fooこのようにして毎回の新しいインスタンスを作成していますが、これはeventプロパティの追加がそのインスタンスにローカライズされていることを意味します。プロトタイプ化されたメソッドはすべてのインスタンスで共有されるため、最適化の観点からはそれほど悪くはありません。

于 2013-06-18T10:33:18.437 に答える
0

関数をそのオブジェクトにバインドする方が簡単かもしれません:

someElement.onEvent = myObject.myHandlerFunction.bind(myObject);

したがって、この関数が呼び出されると、その「this」は myObject になります。

次に、 e.target を使用して要素にアクセスできます。

于 2013-06-18T10:25:14.810 に答える