ES6 变量解构赋值

1.阮一峰老师的es6中说对象解构赋值可以取到继承的属性。同样,也可以取到继承的方法

        const obj1 = {};
        const obj2 = { fooo: 'bar', hello: function(){ console.log("hello")} };
        Object.setPrototypeOf(obj1, obj2);

        const { fooo, hello: helloo } = obj1;
        console.log(fooo); // "bar"
        helloo(); //hello
        function Person(name, age) {
            this.name = name;
            this.age = age;
        }
        Person.prototype.sayName = function () {
            console.log("i am " + this.name);
        }
        function Student(name, age, grade) {
            Person.call(this, name, age);
            this.grade = grade;
        }
        Student.prototype = new Person();

        const s1 = new Student("s1", 1, 1);
        s1.sayName();
        const { sayName: sayname } = s1;
        console.log(sayname, s1);
        sayname.call(s1);

2.函数参数也可以使用默认值,解构失败时,x和y等于默认值。指定参数有两种不同的情况。

私认为,第一种情况时,x、y为两个分开的变量,指定的默认值互相区分。第二种情况时,x、y两个参数集合成一个整体,为move的参数对象,所以不给其中一个变量赋值时为undefined。当参数整体不存在时,才使用整体参数的默认值。

        // 1- 为变量x&y指定默认值
        function move({ x = 0, y = 0 } = {}) {
            return [x, y];
        }
        console.log((move({ x: 3, y: 8 })) instanceof Array); // [3, 8]
        console.log(move({ x: 3 })); // [3, 0]
        console.log(move({})); // [0, 0]
        console.log(move()); // [0, 0]
        console.log("-------------------");

        // 2 - 为move的参数指定默认值
        function move({ x, y } = { x: 0, y: 0 }) {
            return [x, y];
        }
        console.log(move({ x: 3, y: 8 })); // [3, 8]
        console.log(move({ x: 3 }));; // [3, undefined]
        console.log(move({}));; // [undefined, undefined]
        console.log(move());; // [0, 0]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值