質問のタイトルを正しく表現したかどうかはわかりません。明確にするために以下を検討してください...
(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
内にアクセスするfoo
にthis
はどうすればよいですか?object
e
foo
私が思いついた最高のものはこれです
(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
e
e.foo._this
this
e
foo
また、私はこのようなことを避けようとしています...
document.onmousemove = function(e) {
e.foo.bar.call(e);
};
お時間をいただきありがとうございます。