Home >Web Front-end >JS Tutorial >JavaScript practical skills (1)_javascript skills

JavaScript practical skills (1)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:21:081093browse

JavaScript 的成功让人津津乐道,为 Web 网页编写 JavaScript 代码已经是所有 Web 设计师的基本功,这门有趣的语言蕴藏着许多不为人熟知的东西,即使多年的 JavaScript 程序员,也未能完全吃透。本文从7个方面讲述 JavaScript 中那些你不很熟知但非常实用的技巧。

简略语句
JavaScript 可以使用简略语句快速创建对象和数组,比如下面的代码:

var car = new Object();
car.colour 
= 'red';
car.wheels 
= 4;
car.hubcaps 
= 'spinning';
car.age 
= 4;

可以使用简略语句如下:

var car = {
    colour:
'red',
    wheels:
4,
    hubcaps:
'spinning',
    age:
4
}

对象 car 就此创建,不过需要特别注意,结束花括号前一定不要加 ";" 否则在 IE 会遇到很大麻烦。

创建数组的传统方法是:

var arrayTest = new Array(
    
'test1','test2','test3','test4'
);

使用简略语句则:

var arrayTest = ['test1','test2','test3','test4'];

另一个可以使用简略语句的地方是条件判断语句:

var direction;
if(x < 200){
direction
= 1;
}
else{
direction
= -1;
}

//可以简略为:
var direction = x < 200 ? 1 : -1;

JSON 数据格式
JSON 是 "JavaScript Object Notation" 的缩写,由 Douglas Crockford 设计,JSON 改变了 JavaScript 在缓存复杂数据格式方面的困境,如下例,假如你要描述一个乐队,可以这样写:


var band = {
"name":"My name is test1",
"Members":[
{
"name":"name1","role":"role1"},
{
"name":"name2","role":"role2"},
{
"name":"name3","role":"role3"},
{
"name":"name4","role":"role4"}
],
"year":"2010"
}

你可以在 JavaScript 中直接使用 JSON,甚至作为某些 API 的返回数据对象,以下代码调用著名书签网站 delicious.com 的一个 API,返回你在该网站的所有书签,并显示在你自己的网站:
<div id="delicious">div>
<script>
function delicious(o){
   
var out = '
    ';
       
    for(var i = 0;i<o.length;i ){
          out 
    ='
  • ' o[i].u '">' o[i].d '
  • ';
       }
       out 
    = '
';
   document.getElementById(
'delicious').innerHTML = out;
}
script>
<script src="http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious">script>

JavaScript 本地函数 (Math, Array 和 String)
JavaScript 有很多内置函数,有效的使用,可以避免很多不必要的代码,比如,从一个数组中找出最大值,传统的方法是:

var numbers = [3,342,23,22,124];
var max = 0;
for(var i = 0;i<numbers.length;i++){
if(numbers[i] > max){
       max 
= numbers[i];
    }
}
alert(max);

使用内置函数可以更容易实现:

var numbers = [3,342,23,22,124];
numbers.sort(
function(a,b){return b - a});
alert(numbers[
0]);

另一个方法是使用 Math.max() 方法:
Math.max(12,123,2,3,422,4);//return 422

你可以用这个方法帮助探测浏览器

var scrollTop = Math.max(doc.documentElement.scrollTop,doc.body.scrollTop);

这解决了 IE 浏览器的一个问题,通过这种方法,你总是可以找到那个正确的值,因为浏览器不支持的那个值会返回 undefined。

还可以使用 JavaScript 内置的 split() 和 join() 函数处理 HTML 对象的 CSS 类名,如果 HTML 对象的类名是空格隔开的多个名字,你在为它追加或删除一个 CSS 类名的时候需要特别注意,如果该对象还没有类名属性,可以直接将新的类名赋予它,如果已经存在类名,新增的类名前必须有一个空格,用传统的 JavaScript 方法是这样实现的:

function addclass(elm,newclass){
     
var c = elm.className;
     elm.className 
= (c == '')?newclass: c+' '+newclass;
}

使用 split 和 join 方法则直观优雅得多:
function addclass(elm,newclass){
     
var classes = elm.className.split(' ');
     classes.push(newclass);
     elm.className 
= classes.join(' ');
}

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:

  • Create an object called configuration in code
  • It saves all configurations that can be changed, such as CSS ID and class name, button label text, descriptive text, and localized language settings.
  • Set the object as a global object so that others can access and rewrite it directly

You should do this as the last step, here is an article, 5 Things to Do Before Delivering Code Reference for values.
Interaction with the backend
JavaScript is a front-end language. You need other languages ​​​​to interact with the backend and return data. Using AJAX, you can let JavaScript directly interact with the backend and hand over complex data processing. Processed by the background.
JavaScript Framework
Writing your own code to adapt to various browsers is a complete waste of time. You should choose a JavaScript framework and let the framework handle these complex things.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn