JavaScript 中的 Monad [英] Monads in JavaScript

查看:65
本文介绍了JavaScript 中的 Monad的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想了解 JavaScript 中的 monad 有用的实际案例.

So I want to understand the practical cases where monads in JavaScript are helpful.

我阅读了大量有关 JavaScript 中 Monads 的文章,并了解到 jQuery 是其使用示例.但是除了链式"模式,前端工程中使用Monads还能有效解决哪些问题?

I read a bunch on articles on Monads in JavaScript and understand that jQuery is one example of its use. But besides the "chaining" pattern, what other issues can be effectively solved using Monads in front-end engineering?

参考:

http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/

http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html

推荐答案

嗯,我认为第一篇文章很棒而且很详细.它描述了 JQuery 解决的许多问题及其 monad 性质.

Well I think the first article is great and quite detailed. It describes a lot of problems solved by JQuery and its monad nature.

  1. JQuery 包装了 DOM 元素并提供了更丰富的界面.解决的问题很多:更丰富的事件(mouseenter"、mouseleave"、hashchnged"等).事件绑定添加处理程序而不是覆盖.CSS 处理的接口类似于 JQuery 公开的其他接口.

这也是 JQuery 对许多开发人员来说如此直观的原因,因为它只是包装了我们所知道的,而不是试图重新发明 HTML.

This is also the reason JQuery is so intuitive to a lot of developers as it simply wraps what we know and does not try to reinvent HTML.

更不用说它在引用空值时节省了很多错误.如果我没有带有 id guy 的元素,那么运行 $("#guy").text("I am not here") 不会导致错误在 JQuery 中.

Not to mention that it saves a lot of errors when referring to nulls. If I don't have an element with id guy, then running $("#guy").text("I am not here") will not cause an error in JQuery.

  1. JQuery 轻松地将自身包裹在 DOM 元素周围,允许在原始 JS 和 JQuery 界面之间来回遍历.这允许开发人员按照自己的节奏学习 JQuery,而不是一次重写整个代码.

  1. JQuery easily wraps itself around the DOM element allowing to traverse back and forward between raw JS and JQuery's interface. This allows developers to learn JQuery at their own pace instead of rewriting the entire code in one time.

当 JQuery 为回调提供参数时,它使用 DOM 对象而不是 JQuery 的包装器.这允许第 3 方轻松地与 JQuery 集成,因为他们不需要依赖 JQuery.例如,假设我编写了一个使用原始 JavaScript 将文本绘制为红色的函数.functionpaintRed(element){element.style.color="red"} - 我可以轻松地将此函数作为回调传递给 JQuery 函数.

When JQuery feeds a callback with arguments, it uses the DOM object instead of JQuery's wrapper. This allows 3rd-parties to easily integrate with JQuery as they don't need to rely on JQuery. For example lets say I wrote a function that paints text in red using raw JavaScript. function paintRed(element){element.style.color="red"} - I can easily pass this function as callback to a JQuery function.

这篇关于JavaScript 中的 Monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆