Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Simpler method definitions

In ES6, there is a simpler syntax for defining methods when initializing objects, assigning method names directly to functions

const obj = {
  foo() {
    console.log('abc')
  }
}
obj.foo();
Copy the code

The function here is not anonymous. Named functions can be called from the body of a function with an identifier, but anonymous functions cannot

The functions here are also not constructors, so you cannot attempt to instantiate them

So the previous rule was that

const obj = {
  foo: function() {
    console.log('abc')
  }
}
obj.foo();
Copy the code

Async method

Async methods can also be defined in shorthand syntax

const obj = {
  foo: async function() {
    awaitsome_promise; }}// Abbreviate syntax
const obj = {
  async foo() {
    awaitsome_promise; }}Copy the code

Take a chestnut

var obj = {
  a : "foo".b(){ return this.a; }};console.log(obj.b()); // "foo"
Copy the code

The direct method is called, and this refers to the object itself

const p = obj.b;
p();  // undefined
Copy the code

This. A is undefined because p is called on window and this refers to window

var bar = {
  foo0: function() { return 0; },
  foo1() { return 1; },'foo' + 2] () {return 2; }};console.log(bar.foo0()); / / 0
console.log(bar.foo1()); / / 1
console.log(bar.foo2()); / / 2
Copy the code

[‘foo’ + 2] : [‘foo’ + 2] : [‘foo’ + 2] : [‘foo’ + 2] : [‘foo’ + 2]

var bar = {
  foo0: function() { return 0; },
  foo1() { return 1; },'foo' + 2] :function () { return 2; }};console.log(bar.foo0()); / / 0
console.log(bar.foo1()); / / 1
console.log(bar.foo2()); / / 2
Copy the code

Browser compatibility

Except ie mainstream browsers have all supported, you can rest assured to use ~

reference

Developer.mozilla.org/zh-CN/docs/…

The above is a small knowledge point, ES6 shorter method definition introduction, can be used in the development of it, welcome to comment and like ~