Ter*_*rry 5 javascript methods inheritance this
我不确定我是否正确地表达了问题标题; 请考虑以下内容以澄清......
(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();
};
Run Code Online (Sandbox Code Playgroud)
我怎样才能访问this方法/道具,foo但是this引用了初始的objectaka 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();
};
Run Code Online (Sandbox Code Playgroud)
我现在有工作,但我担心两件事情... ...
1分配的递归引用e到e.foo._this
和
2分配的冗余e来e.foo._this,如果this可以访问的e,而不是foo它将使"东西"更高性能,特别是关于像mousemove事件这样的事情.
另外,我试图避免这样的事情......
document.onmousemove = function(e) {
e.foo.bar.call(e);
};
Run Code Online (Sandbox Code Playgroud)
所有的建议都表示赞赏,感谢您的时间.
通过对你所拥有的进行细微的改变,你可以让事情变得更简单:
(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();
};
Run Code Online (Sandbox Code Playgroud)
然而,这正在对共享对象进行更改foo,您可能希望重写一些内容,以便e.foo()返回一个新实例foo,并将其他方法移至foo'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);
};
}());
Run Code Online (Sandbox Code Playgroud)
这样,您foo每次都会创建一个新实例,但这意味着您添加的event属性将本地化到该实例;原型方法将在所有实例之间共享,因此从优化的角度来看这并不算太糟糕。
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |