Home >Web Front-end >JS Tutorial >JavaScript practical skills (1)_javascript skills
JavaScript 的成功让人津津乐道,为 Web 网页编写 JavaScript 代码已经是所有 Web 设计师的基本功,这门有趣的语言蕴藏着许多不为人熟知的东西,即使多年的 JavaScript 程序员,也未能完全吃透。本文从7个方面讲述 JavaScript 中那些你不很熟知但非常实用的技巧。
简略语句
JavaScript 可以使用简略语句快速创建对象和数组,比如下面的代码:
可以使用简略语句如下:
对象 car 就此创建,不过需要特别注意,结束花括号前一定不要加 ";" 否则在 IE 会遇到很大麻烦。
创建数组的传统方法是:
使用简略语句则:
另一个可以使用简略语句的地方是条件判断语句:
JavaScript 本地函数 (Math, Array 和 String)
JavaScript 有很多内置函数,有效的使用,可以避免很多不必要的代码,比如,从一个数组中找出最大值,传统的方法是:
使用内置函数可以更容易实现:
你可以用这个方法帮助探测浏览器
这解决了 IE 浏览器的一个问题,通过这种方法,你总是可以找到那个正确的值,因为浏览器不支持的那个值会返回 undefined。
还可以使用 JavaScript 内置的 split() 和 join() 函数处理 HTML 对象的 CSS 类名,如果 HTML 对象的类名是空格隔开的多个名字,你在为它追加或删除一个 CSS 类名的时候需要特别注意,如果该对象还没有类名属性,可以直接将新的类名赋予它,如果已经存在类名,新增的类名前必须有一个空格,用传统的 JavaScript 方法是这样实现的:
Event proxy
Instead of designing a bunch of events in the HTML document, it is better to design an event proxy directly. For example, if you have some links, the user does not want to open the link after clicking it, but executes an event, HTML code As follows:
Traditional event processing is to traverse each link and add its own event processing:
Use events Proxies can be processed directly without traversing:
Anonymous functions and Module mode
A problem with JavaScript is that any variable, function or object unless it is inside a function The definition, otherwise, is global, meaning that other code on the same page can access and overwrite this variable (ECMA's JavaScript 5 has changed this situation - Translator), using anonymous functions, you can Bypass this problem.
For example, if you have a piece of code like this, obviously the variables name, age, status will become global variables
To avoid this problem, you can Use an anonymous function:
If this function will not be called, it can be more direct:
If you want to access The objects or functions can be:
This is the so-called Module pattern or Singleton pattern (Singleton). This pattern is recommended by Douglas Crockford and has been widely used in Yahoo User Interface Library YUI.
If you want to call the methods inside elsewhere, but don’t want to use the object name myApplication before the call, you can return these methods in an anonymous function, or even return them with abbreviations:
Code Configuration
When others use the JavaScript code you wrote, they will inevitably change some of the code, but this will be difficult because not everyone can easily read other people's code. Instead of doing this, Create a code configuration object. Others only need to change certain configurations in this object to implement code changes. Here is an article detailed explanation of JavaScript configuration objects. In short: