我不确定我是否正确地表达了问题标题;请考虑以下内容以澄清……
(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();
};
我如何在foo的方法/道具中访问这个,但是这个引用了初始对象aka 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.将e赋给e.foo._this的递归引用
和
2.将e分配给e.foo._this的冗余,如果这可以作为e而不是foo访问,那么它将使“事物”更具性能,特别是在像mousemove事件这样的事情上.
另外,我试图避免这样的事情……
document.onmousemove = function(e) {
e.foo.bar.call(e);
};
所有的建议都表示赞赏,感谢您的时间.
最佳答案
通过对您拥有的内容进行微妙的更改,您可以使事情变得更简单:
(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()返回foo的新实例,并将您的其他方法移动到foo的原型.
(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实例,但这意味着您添加的事件属性已本地化为该实例;原型方法将在所有实例之间共享,因此从优化的角度来看也不算太糟糕.