【问题标题】:In javascript, what's the difference between an instance function and instance variable of type Function?在javascript中,实例函数和函数类型的实例变量有什么区别?
【发布时间】:2021-05-03 16:58:06
【问题描述】:

我知道其中一个区别是 Function 类型的实例变量自动绑定到类。例如:

class Dog {
  sound = 'woof'
  bark() {
    console.log(this)
  }
  boundBark = () => {
    console.log(this)
  }
}

const fido = new Dog()
fido.bark() // woof
fido.boundBark() // woof
const bark = fido.bark
bark() // undefined
const boundBark = fido.boundBark
boundBark() // woof
Dog { sound: 'woof', boundBark: [Function: boundBark] }
Dog { sound: 'woof', boundBark: [Function: boundBark] }
undefined
Dog { sound: 'woof', boundBark: [Function: boundBark] }

为什么会这样?这两种编写实例函数的方式还有其他区别吗?

【问题讨论】:

  • 调用箭头函数不会建立this绑定。
  • bark 是存在于Dog 原型上的方法,在所有实例之间共享。 boundBark 是一个实例属性,它包含一个箭头函数,每个实例都有一个。
  • "Function 类型的实例变量自动绑定到类" 如果这里的“实例变量”是一个自己的属性,只有当该方法直接在类中用箭头函数定义。
  • @Pointy 另外,我相信您的解释并不准确。箭头函数是唯一真正保留 this 绑定的函数。
  • @Tim 不,Pointy 完全正确。请参阅How does the “this” keyword work? 以获得更完整的说明,但非箭头 函数将在调用时确定this 的值。箭头函数不是这样——调用它们不会改变this。

标签: javascript function this bind


【解决方案1】:

您可以检查这些方式对Dog.prototype 对象的作用:

方法定义:

class Dog {
  bark() {
    console.log(this) // *this* referss to the actual instance
  }
}

console.log(Dog.prototype.bark); // function bark

Public class field [MDN]:

class Dog {
  bark = () => {
    console.log(this); // also, *this* refers to the actual instance
  }
}

console.log(Dog.prototype.bark); // undefined

在第一种情况下,您在类原型中定义一个函数,而在后一种情况下,您在“构造函数时”在实例中定义变量,就像任何其他变量一样。

后者同做:

class Dog {
  constructor() {
    
    this.bark = () => {
      // this is the reason why *this* is actually available
      // and refers to the actual instance
      console.log(this);
    }
    
    /* The rest of defined constructor */
  }
}

console.log(Dog.prototype.bark); // undefined

记住Public class fields 还没有在ECMAs 标准中引入,所以很多JS环境不能支持它们,你应该使用像Babel这样的工具来实现向后兼容。由于这个原因,一些行为仍然依赖于应用程序(例如定义优先级)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2019-05-19
    • 2013-10-08
    • 2010-10-23
    • 2012-02-08
    相关资源
    最近更新 更多