JavaScript语言规范

块内函数声明

  各引擎对于块内函数声明的实现都不一样,和 EcmaScript 的建议相违背。 ECMAScript 只允许在根脚本语句或其他函数中进行函数声明,如果一定要用的话可以在块内用变量来定义函数,防止函数申明提升

//错误方法
f (x) {
  function foo() {}
}

//正确方法
if (x) {
  var foo = function() {}
}

  

基本包装类型

typeof Boolean(0) == 'boolean';         //true
typeof new Boolean(0) == 'object';    //true

var a=Boolean(0);      //boolean
var b=new Boolean(0);   //object

if(a){
     console.log(1);  //执行      
}

if(b){
     console.log(1);  //不执行      
}

  

方法定义

  var Foo=function(name){
        this.name=name;
    };
    Foo.prototype.bar = function(){
        console.log("add function to protype,and this will be inherited by the new instance");
    };
    var b=new Foo("aa");
    b.bar();

  

True 和 False 布尔表达式

以下的表达式都返回false:

  • null
  • undefined
  • '' 空字符串
  • 0 数字0

以下的都返回true:

  • '0' 字符串0
  • [] 空数组
  • {} 空对象

&& 和 ||

  常见用法是利用&& 和 ||的短路运算法则

if (node) {
  if (node.kids) {
    if (node.kids[index]) {
      foo(node.kids[index]);
    }
  }
}

//可简写成
if (node && node.kids && node.kids[index]) {
  foo(node.kids[index]);
}

  

 

posted on 2016-08-26 15:49  carlyin  阅读(186)  评论(0)    收藏  举报

导航