ES6--对象、函数的扩展

来源:互联网 发布:电脑看电视软件收台多 编辑:程序博客网 时间:2024/04/30 08:07

七、对象的扩展

ES6中为对象属性和方法提供了简洁的方式,表达式作为属性名变成可能,并提供了name属性返回函数名。

属性的简洁表示法

const name = 'ligang';const person = {    name,    sayName() {        console.log(this.name);    }};

属性名表达式

const propKey = 'name';const person = {  [propKey]: "ligang",  ['a' + 'ge']: 27}

方法的name属性

var doSomething = function() {}doSomething.name; // "doSomething"(new Function()).name;  // "anonymous"

取值函数

存值函数在方法名的前面加上set;取值函数在方法名的前面加上get。

var person = {    set name(n) {        this.n = n;    },    get name() {        return this.n;    }};console.log(person.name); // undefinedperson.name = 'ligang';console.log(person.name); // "ligang"

Object.is()

用来比较两个值是否严格相等。它与严格比较运算符(===)的行为基本一致,不同之处只有两个:一是+0不等于-0,二是NaN等于自身。

+0 === -0;  // trueObject.is(+0, -0); // falseNaN === NaN;  // falseObject.is(NaN, NaN); // true

Object.assign()

用来将源对象(source)的所有可枚举属性,复制到目标对象(target)。

var target = { a: 1 };var source1 = { b: 2 };var source2 = { c: {d: 4} };Object.assign(target, source1, source2);target // {a:1, b:2, c:{d: 4}}

注意: Object.assign方法实行的是浅拷贝,而不是深拷贝。也就是说,如果源对象某个属性的值是对象,那么目标对象拷贝得到的是这个对象的引用。

用途(1):为对象添加属性

class Point {  constructor(x, y) {    Object.assign(this, {x, y});  }}

用途(2):为对象添加方法

Object.assign(SomeClass.prototype, {  someMethod(arg1, arg2) {},  anotherMethod() {}});

用途(3):克隆对象

function clone(origin) {  return Object.assign({}, origin);}

用途(4):合并多个对象

const merge = (target, ...sources) => Object.assign(target, ...sources);

用途(5):为属性指定默认值

const DEFAULTS = {  logLevel: 0,  outputFormat: 'html'};function processContent(options) {  options = Object.assign({}, DEFAULTS, options);}

__proto__属性

该属性被大部分浏览器实现,但其并没有被ES6正式收录。所以不建议直接使用该属性,而是使用Object.setPrototypeOf()(写操作)、Object.getPrototypeOf()(读操作)、Object.create()(生成操作)代替。

function A(){}A.prototype.say = function(){console.log("A");};function B(){}B.prototype.say = function(){console.log("B");};var obj = Object.create(A.prototype);obj.say();  // "A"Object.getPrototypeOf(obj); // Object(A)Object.setPrototypeOf(obj, B.prototype);obj.say();  // "B"Object.getPrototypeOf(obj); // Object(B)

对象的扩展运算符

ES7提案将rest参数引入对象,目前Babel已经支持这项功能。

let z = { a: 3, b: 4 };let n = { ...z };n // { a: 3, b: 4 }

八、函数的扩展

函数参数默认值

ES6之前不能直接为函数的参数指定默认值,只能采用变通的方法,通过“||”来规避,如下:

function log(x, y) {  y = y || 'World';  console.log(x, y);}

但上述存在一个问题,当y对应的布尔值为false,则该赋值不起作用。

log('Hello',0);// Hello World

面对上述问题,我们通常会:

// 写法一if (typeof y === 'undefined') {    y = 'World';}// 写法二if (arguments.length === 1) {    y = 'World';}

在ES6中允许为函数的参数设置默认值,即直接写在参数定义的后面。

function log(x, y = 'World') {  console.log(x, y);}

rest参数

ES6引入rest参数(形式为“…变量名”),用于获取函数的多余参数,这样就不需要使用arguments对象了。

function add(...values) {  let sum = 0;  for(let val of values) {    sum += val;  }  return sum;}

注意:

  • rest参数之后不能再有其他参数(即只能是最后一个参数),否则会报错;
  • 函数的length属性,不包括rest参数。

扩展运算符

扩展运算符(spread)是三个点(…)好比rest参数的逆运算,将一个数组转为用逗号分隔的参数序列。

// 等价于Math.max(14, 3, 77)Math.max(...[14, 3, 77]); // 与解构赋值结合起来,用于生成数组const [first, ...rest] = [1, 2, 3, 4, 5];  

箭头函数

(1)使用语法

方式一:单一参数的单行箭头函数
语法:arg => statement
示例:

const fn = x => x + 1;fn(1); // 2

方式二:多参数的单行箭头函数
语法:(arg1, arg2) => statement
示例:

const fn = (x, y) => x + y;fn(1, 1); // 2

方式三:多行箭头函数
语法:

arg => {}(arg1, arg2) => {}

示例:

const fn = (x, y) => {  return x + y;}fn(1, 1); // 2

方式四:无参数箭头函数
语法:() => statemnt
示例:

const fn = () => console.log("hello");fn(); // "hello"

(2)this穿透
箭头函数会将函数内部的this延伸至上一层作用域中,即上一层的上下文会穿透到内层的箭头函数中。

// ES5var name = "window";var obj = {  name: "obj",  sayName: function(){    return function(){      console.log(this.name);    }  }};var sayname = obj.sayName();sayname();  // "window"sayName.call(obj); // "obj"// ES6var name = "window";var obj = {  name: "obj",  sayName: function(){    return () => console.log(this.name);  }};var sayname = obj.sayName();sayname();  // "obj"sayname.call(obj);  // "obj"

(3)注意事项

  • 箭头函数对上下文的绑定是强制的,无法通过apply或call方法改变。见上述示例
  • 因为箭头函数绑定上下文的特性,故不能随意在顶层作用域使用箭头函数
var name = "window";var obj = {  name: "obj",  sayName: () => console.log(this.name)}obj.sayName();  // "window"// ES5等价方式var name = "window";var that = this;var obj = {  name: "obj",  sayName: function(){    console.log(that.name);  }}obj.sayName();  // "window"
  • 箭头函数中没有arguments、callee、caller等对象
var fn = () => {  console.log(arguments);}fn(1, 2);  // Uncaught ReferenceError: arguments is not defined

可以通过参数列表代替实现

var fn = (...args) => {  console.log(args);}fn(1, 2);  // [1, 2]

注意: arguments在箭头函数中,会跟随上下文绑定到上层,所以在不确定上下文绑定结果的情况下,尽可能不要在箭头函数中使用arguments,而要使用…args。

多返回值

方式一:使用对象作为返回载体

Syntax: {arg1, arg2} = {arg1: value1, arg2: value2}

function test() {    return {        name: 'ligang',        age: 27    };}const {name, age} = test();// const {age, name} = test();console.log(name, age); // ligang 27

方式二:使用数组作为返回载体

数组作为返回载体与使用对象作为返回载体区别是:数组需要让被赋予的变量(或常量)名按照数组的顺序获取。

Syntax: [arg1, arg2] = [value1, value2]

function test() {    return ["liang", 27];}const [name, age] = test();console.log(name, age); // ligang 27

Syntax: [arg1, ,arg2] = [value1, value2, value3]

function test() {    return ["liang", "male", 27];}const [name, ,age] = test();console.log(name, age); // ligang 27

Syntax: [arg1, ...resetArgs] = [value1, value2, value3]

function test() {    return ["liang", "male", 27];}const [name, ...others] = test();console.log(name, others); // liang ["male", 27]
1 0
原创粉丝点击