To love. To succeed. To be honest. 网摘

JS规则

1. 变量命名规则

  • 第一个字符必须是字母、下划线(_)或美元符号($)以美元开头,很诱人有木有:-D)
  • 余下的字符可以是下划线、美元符号或任何字母或数字字符

 

2. 变量声明会被提升到当前作用域的顶部

var scope = 'global';

function f () {
       console.log(scope);  // "undefined", not "global"
       var scope = 'local';
       console.log(scope);  //  "local"
       var name = 'country';
    }

f();

  以上的输出分别为undefined和local,说明f的声明被提前到当前作用域前面去了。

这里涉及一个JavaScript很有趣的现象—提升(hoisting),函数内部声明的所有变量对整个函数作用域都是可见的,就好像在函数执行时,所有的变量声明会被提升到第一行一样。

 

3.闭包

    阮一峰的 学习Javascript闭包(Closure)

    深入理解Javascript闭包

    酷客 理解Javascript的闭包

    <JavaScript权威指南(第5版)> Chapter8.6 闭包

 

4.关于窗口xy的事:http://www.qianyunlai.com/post-574.html

5.计算文本字符串宽度(中文占2格):

function getStringWidth(str) {
    var width = len = str.length;
    for(var i=0; i < len; i++) {
        if(str.charCodeAt(i) >= 255) {
            width++;
        }
    }
    return width;
}

  

6.javascript脚本加载,异步加载方式: ie4,firefox 加入’defer‘属性; html5 支持 <script async=“true” />

   【带有 defer 属性的<script>元素在 onload 事件被触发被调用】

   【在有 async 的情况下,JavaScript 脚本一旦下载好了就会执行,所以很有可能不是按照原本的顺序来执行的。如果 JavaScript 脚本前后有依赖性,使用 async 就很有可能出现错误。

     JavaScript 的性能优化:加载和执行 - WEB开发者

 

7.获取id的函数: 简单多了

  var el=document.getElementById;
  var day = el('day');
 
8.JS的this规则:指向当前引用它的对象。
   对于this,内嵌函数的形式要注意其指向,常用一个变量来重定向来避免错误:
   
var name = "clever coder";  
var person = {  
    name : "foocoder",  
    hello : function(sth){  
        var sayhello = function(sth) {  
            console.log(this.name + " says " + sth);  
        };  
        sayhello(sth);  
    }  
}  
person.hello("hello world");//clever coder says hello world

  例子中,高亮的 sayhello(sth)调用时候,处于hello的函数体内,此时sayhello函数里的this没有name的属性,则会直接指向全局变量(window)的name“clever coder”。为此,解决这个错误,使用that或self来纠正,如下:

var name = "clever coder";  
var person = {  
    name : "foocoder",  
    hello : function(sth){  
        var that = this;  
        var sayhello = function(sth) {  
            console.log(that.name + " says " + sth);  
        };  
        sayhello(sth);  
    }  
}  
person.hello("hello world");//foocoder says hello world

  以上引用自拔刺的博文谈谈Javascript的this指针

 

9. typeof sth返回的结果是一个string类型,即typeof typeof x === 'string'

posted @ 2013-07-31 19:29  RaynerBan  阅读(235)  评论(0编辑  收藏  举报

To love. To succeed. To be honest.