es6(4)学习笔记:数值扩展,函数扩展(箭头函数)

157 阅读2分钟

数值扩展

// es5
parseInt(12.222) //12
parseFloat(12.3333) /12.3333

//es6 
Number.parseInt(12.222) //12
Number.parseFloat(12.3333) /12.3333
// 用来判断一个数值是否为整数  返回boolean
Number.isInteget(20) // true
Number.isInteget(20.0) // true
Number.isInteget(20.12) // false
Number.isInteget('20.12') // false

Math.ceil()//向上取整
Math.floor()//向下取整
Math.round()//四舍五入

// es6
Math.trunc(4.1) //4 去除小数点返回整数部分
Math.sign(-4.1) // 判断一个数是正数 负数或零 对于非数值,会将其转换为数值 返回值: 正数+1 负数-1 零0 其他值 NaN

//指数运算符(幂) **
2**2 //4

函数扩展

//es5
function fun(x,y){
    y = y || 10;
    console.log(y)
}
//es6
function fun(x, y = 10){
    console.log(y)
}
 
// arguments 类似与数组 是一个对象并不是数组
function fun2(){
    console.log(arguments[6])
    console.log(arguments.push(10)) // error 因为arguments不是数组,不能直接使用数组中的方法和属性
}
fun2(12,21,3,3,34);

// rest参数
function fun3(...value){
    console.log(value)
    value.push(10)
    console.log(value)
    var n = 0;
    for(var v of value){
        n+=v;
    }
    return n;
}
fun3(12,21,3,3,34);

箭头函数

let f1 = () = > {return 123}
//返回对象
let f2 = (n1,n2) => ({name:n1,age:n2})
let f3 = (n1,n2) => {
    var obj = {
        name: n1,
        age: n2
    }
    return obj;
}

箭头函数要注意的几点

  1. 箭头函数不能作为构造函数,不能使用new let f = () => {};var f1 = new f(); // error
  2. 箭头函数没有原型对象
  3. 箭头函数this指向

箭头函数中this的指向是,定义时的this,而不是执行时的this(外层的调用者)

function Person(){
    this.age = 18;
    setTimeout(function () {
        console.log(this) //this指向window 相当于window直接调用setTimeout里的funciton,定时器回调函数this都指向window
    },2000)
    
    setTimeout(() => {
        console.log(this) //this指向Person
    },2000)
}
var p = new Person();

// 箭头函数,当成一个方法使用。作为方法的箭头函数的this指向,是指向全局window对象的,普通函数指向调用它的对象
var obj = {
    age: 17,
    fun: function(){
        console.log(this.age) // 17
    },
    fun2: function (){
        var fn = () = this.age; // this指向obj
        return fn;
    },
    fun3: () => {
        console.log(this) //this指向window
    }
}

arguments参数 箭头函数没有绑定arguments对象

var f5 = () => {
    console.log(arguments)
}
f5(2,3,4,5,6,54,2345) // arguments is not defined