JavaScript 方法链
我一直在尝试找到一种方法,以类似于 jQuery 的方式将这些方法链接在一起。这是我的意思的一个例子:
(function() {
window.foo = function foo( id ) {
if( window == this )
return new foo( document.getElementById( id ) );
this.alert = function() {
alert( object.value );
}
}
}());
foo('input').alert();
所以正如你所看到的,我想使用作为警报函数的一部分传递到类中的对象,但我不想通过 将其存储在类中this.object = id
,然后执行 alert( this.object.value );
什么是解决此问题的优雅方法?
I have been trying to find a way to chain these methods together in a similar way to jQuery. here is an example of what I mean:
(function() {
window.foo = function foo( id ) {
if( window == this )
return new foo( document.getElementById( id ) );
this.alert = function() {
alert( object.value );
}
}
}());
foo('input').alert();
So as you can see, I would like to use the object that was passed into the class as part of the alert function, but I do not want to store it in the class via this.object = id
, and then do alert( this.object.value );
What would be an elegant way to go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
jQuery 仅通过从其许多方法返回相同的 jQuery 对象来进行链接。您的方法并不总是返回值,因此它不会可靠地链接。如果您始终让它返回相同类型的值,则链接可能开始有意义。
jQuery only chains by returning the same jQuery object from many of its methods. Your method doesn't always return a value, so it won't chain reliably. If you always have it return a value of the same type, chaining may begin to make sense.
您不需要在对象中存储引用,因为您已经将其作为
id
。You don't need to store a reference in the object, because you already have it as
id
.