Difference between nameFunction() {} and nameFunct

2020-08-23 01:12发布

问题:

I'm start learning Vue.js and ECMA6 syntax, I saw this in the tutorial:

methods: {
  someMethod: function() { 
    console.log(this) // this works
  }
} 

Then I thought the syntax could be:

methods: {
  someMethod: () => {
    console.log(this) // this undefined
  }
}

but this works:

methods: {
  someMethod () {
    console.log(this) // this works
  }
}

Can explain the difference and the ECMA5 syntax?

回答1:

Of your three options, only the first one is supported in ES5. The other two are additions in ES6.

The third option is an ES6 shortcut for the first option and thus they work identically in ES6.

When you use the arrow syntax as in the second one, this is NOT set to be the host object as it is in your first and third. That's one of the features of the arrow syntax and thus it should not be used when you expect this to be set to the host object. Instead, this will be set to the lexical context from where the code was defined - often referred to as "the value of this in the enclosing context" or the "lexical value of this" which in your case would be whatever this was when the host object was initially declared which apparently was undefined.

Here's a good reference article on arrow functions: ES6 In Depth: Arrow functions



回答2:

  1. Object methods that has method someMethod. In this case this is a link to object methods.
  2. Object methods that has property someMethod that stores some anonymous function. In this function this is undefined because function is anonymous.
  3. Object methods has internal function someMethod. In this function this is link to methods, because it's internal named function (not anonymous or external) of this object.

Good luck!

+ Try this way

var methods1 = function() {
  var self = {
    someMethod: function() { 
      console.log(self);
    }
  };
  return self;
}();
    
var methods2 = function() {
  var self = {
    someMethod: () => { 
      console.log(self);
    }
  };
  return self;
}();

var methods3 = function() {
  function someOtherMethod() {
    console.log(self);
  }
  var self = {
    someMethod: function() { 
      someOtherMethod();
    }
  }
  return self;
}();

methods1.someMethod();
methods2.someMethod();
methods3.someMethod();