我不确定我是否正确地表述了问题标题;请考虑以下内容以澄清...
(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
akae
而不是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);
};
感谢您的所有建议,感谢您的宝贵时间。