ES6-形参默认值

在定义一个函数的时候,我们定义了几个函数的参数,但是在调用的时候我们可能并没有传入足够的参数,那么未被满足的参数的值就是undefined,在ES6中如果有这种情况我们可以给形参一个默认值,如果该形参在调用函数的时候未被赋值,那么它的值就是我们定义的默认值而不是undefined。

例:

         function Point(x,y){
            this.x = x;
            this.y = y;
        }


        function Point1(x=0,y=0){
            this.x = x;
            this.y = y;
        }

        var p = new Point();
        var p1 = new Point1();
        console.log(p);
        console.log(p1);
输出:
  1. Point
    1. x: undefined
    2. y: undefined
  1. Point1
    1. x: 0
    2. y: 0

猜你喜欢

转载自www.cnblogs.com/maycpou/p/12335282.html