美文网首页
2018-05-11

2018-05-11

作者: iOneWay | 来源:发表于2018-05-11 13:33 被阅读12次

1、JS中的分号陷阱

javascript引擎有一个在行末自动添加分号的机制,这可能让你栽倒return语句的一个大坑:

function foo() {
      return { name: 'foo' };
}
foo();    // { name: 'foo' }

如果把return语句拆分两行:

function foo() {
    return     // 自动添加了分号,相当于return undefined;
        { name: 'foo' };   // 这行语句已经没法执行到了
}
foo(); // undefined

所以正确的多行写法是:

function foo() {
    return { // 这里不会自动加分号,因为{表示语句尚未结束
        name: 'foo'
    };
}

2、函数定义的几种方式

1,方式一

function abs(x) {

}

2, 方式二、

var abs = function (x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
};

在这种方式下,function (x) { ... }是一个匿名函数,它没有函数名。但是,这个匿名函数赋值给了变量abs,所以,通过变量abs就可以调用该函数。
上述两种定义完全等价,注意第二种方式按照完整语法需要在函数体末尾加一个;,表示赋值语句结束。

对象中的方法和属性定义

1, ES6中方法的定义

// 简写定义对象中的方法
const o = {   
  method() {
    return "Hello!";
  }
};

// 等同于
const o = {
  method: function() {
    return "Hello!";
  }
};

2, ES6中属性的简写定义

let birth = '2000/01/01';

const Person = {

  name: '张三',  //属性的正常定义

  //属性的简写定义,等同于birth: birth
  birth,

  // 等同于hello: function ()...
  hello() { console.log('我的名字是', this.name, '年龄', this.birth); }
};

ES6 rest参数

function foo(a, b, ...rest) {
    console.log('a = ' + a);
    console.log('b = ' + b);
    console.log(rest);
}

foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [ 3, 4, 5 ]

foo(1);
// 结果:
// a = 1
// b = undefined
// Array []

var变量提升

注意:var变量提升只会提升变量声明,不会提升变量赋值

var a = b +" world"
var b = "hello"
console.log(a)  //undefined world

如果var变量没有声明,则报错:

var a = b +" world"
// var b = "hello"
console.log(a)   //报错: ReferenceError: b is not defined

相关文章

网友评论

      本文标题:2018-05-11

      本文链接:https://www.haomeiwen.com/subject/orlfdftx.html