ES6_轻松定义对象函数、对象文字

《定义对象函数》

在RS5中,定义对象中的函数时,我们使用function关键字:

const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};

而在ES6中,我们在对象中定义函数时,可以去掉函数关键字function和冒号:

const person = {
  name: "Taylor",
  sayHello() {
    return `Hello! My name is ${this.name}.`;
  }
};

再看一个具体例子:

/*
//ES5中的对象函数定义:
const bicycle = {
  gear: 2,
  setGear: function(newGear) {
    this.gear = newGear;
  }
};
*/
//ES6中的对象函数定义:
const bicycle = {
  gear: 2,
  setGear(newGear) {
    this.gear = newGear;
  }
};

//测试:
bicycle.setGear(3);
console.log(bicycle.gear); //3

。。。

《定义对象文字》

const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

上面这种定义对象文字的方法很冗余,x:x,要写两遍,而ES6提供了新方法,只需写一遍x,它就会被转换为x:x(或等效的东西)。下面是上面重写的相同函数

const getMousePosition = (x, y) => ({ x, y });

用对象属性速记编写简洁的对象文字声明:

//未使用ES6新方法的代码:
const createPerson = (name, age, gender) => { return { name: name, age: age, gender: gender }; }; //在ES6中,上面代码可以简写成下面的形式: const createPerson = (name, age, gender) => ({ name, age, gender }); // 测试: console.log(createPerson("Zodiac Hasbro", 56, "male")); //{ name: 'Zodiac Hasbro', age: 56, gender: 'male' }

 。。。

posted @ 2022-09-15 10:12  枭二熊  阅读(105)  评论(0编辑  收藏  举报