我有一个嵌入在其他网站上的 JavaScript 小部件(一段嵌入的 JS 和 HTML 代码).我应该怎么做才能确保它的变量名不会与托管页面变量发生冲突?
I have a JavaScript widget (a piece of embedded JS and HTML code) that's embedded on other sites. What should I do to make sure it's variable names don't clash with the hosting page variables?
我希望这个小部件内联",意思是与托管页面在同一页面上,不是在 iframe 中,避免与托管页面发生名称冲突或冲突的最佳方法是什么与其他小部件?
I'd like this widget to be "inlined" meaning on the same page as the hosting page, not in an iframe, what's the best way to avoid name clashes with the hosting page or clashes with other widgets?
名称冲突可能以多种方式发生:
Name clashes can happen in several ways:
我可以想到几种避免名称冲突的方法,但我想知道是否有最佳实践或其他一般性建议.所以这是我的 2c:
I can think of several ways to avoid name clashes, but I was wondering if there's a best-practice or other general recommendations. So here's my 2c:
Javascript 命名空间:
Javascript namespaces:
http://www.codeproject.com/KB/scripting/jsnamespaces.aspx
它在几个 javascript 框架/库中大量使用,例如 YUI:http://developer.yahoo.com/yui/yahoo/
It is heavily used in several javascript frameworks/libraries, such as YUI: http://developer.yahoo.com/yui/yahoo/
这篇关于如何避免 JavaScript 小部件中的名称冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!