这些功能方法形式之间是否有真正的区别/特色?

问题描述

关于要从对象外部“调用”的方法,我可以说下面这三种方式在我的代码内部起相同作用吗?

示例:

var boat = 
{
  peter: () => {console.log("a")},james: function() {console.log("b")},john() {console.log("c")}
}

无论如何,这些都是我知道如何在对象/变量内部应用函数的方式...

我想知道每种形式是否存在主要差异,因为这三种形式的调用方式相同:

boat.peter();
boat.james();
boat.john();

解决方法

在您的示例中没有区别,但是如果您观看此示例

const obj = {
  someVar: 100,// this = obj here => the log will print '100' because obj have someVar
  functionLog: function () {
    console.log(this.someVar);
  },// this = global (widnow) here => the log will print undefined because doesn't have someVar
  // this is the same as writing varName: function () {console.log(this.someVar);}.bind(window) or
  // function () {console.log(this.someVar);}.bind(this) while this = global (window)
  arrowLog: () => console.log(this.someVar),// this = obj here => the log will print '100' because obj have someVar
  // this is a prettier way to write a regular function in es6,when compiled to es5,it'll look just like functionLog
  memberFunctionLog() {
    console.log(this.someVar); // this = obj here
  }
}

obj.arrowLog();
obj.functionLog();
obj.memberFunctionLog();

箭头函数就像绑定到特定作用域的常规函数​​一样,作用域将是您声明它的位置的作用域,它在类中非常有用

class A {
  constructor() {
    this.someVar = 100;
    this.arrowLog = () => console.log(this.someVar);
  }
  
  memberLog() {
    console.log(this.someVar);
  }
}

const a = new A();

const arrowLog = a.arrowLog;
const unbindedLog = a.memberLog;
const bindedLog = a.memberLog.bind(a); // Just like an arrow function,keeps it's scope

arrowLog(); // will print 100,because the arrow function was declared where this = specific instance of A,and arrow function keeps it's scope

// unbindedLog(); // will print undefined,because unbindedLog was declared where this = global (window) and memberLog is not an arrow function

bindedLog(); // Will print 100,because it was binded with a,so this = a