【问题标题】:JS Class: Difference between ES6 myFunc(){..} and ES5 myFunc = function() {...} in a class declaration [duplicate]JS 类:类声明中 ES6 myFunc(){..} 和 ES5 myFunc = function() {...} 之间的区别 [重复]
【发布时间】:2019-12-04 22:27:54
【问题描述】:

在下面的代码中,

class PersonClass {
  constructor(fname) {
    this.fname = fname;
  }
  read = function() { console.log('I am reading') }
  speak () { console.log('I am speaking'); }
}

//Instantiate 
let p1 = new PersonClass('Raj')

read = function() { console.log('I am reading') } 成为新创建实例的属性,即

p1.hasOwnProperty('read')true

相对于speak() { console.log('I am speaking'); } 被分配给PersonClass.prototype。即

p1.hasOwnProperty('speak')False

p1.__proto__.hasOwnProperty('speak')true

有人能解释一下为什么会这样吗?

本质上,类中的两种方法声明方式之间的区别是什么。

我认为 speak() {...} 只是 speak = function() {...} 的较短语法(在 ES6 中)

谢谢

【问题讨论】:

  • 因为js遵循原型继承。
  • 不,方法语法不是类属性的缩写。
  • 类主体中的variableName = ... 语法等同于constructor 中的this.variableName = ... 语句。

标签: javascript es6-class function-expression class-fields


【解决方案1】:

read = function() { console.log('I am reading') }

是新的类字段语法。它实际上与在构造函数中分配给实例的 read 属性相同:

class PersonClass {
  constructor(fname) {
    this.read = function() {
      console.log('I am reading')
    }
    this.fname = fname;
  }
  speak() {
    console.log('I am speaking');
  }
}

另一方面,speak 是一个普通的类方法,也就是说它在原型上,PersonClass.prototype,与Object.getPrototypeOf(p1) 相同,与p1.__proto__ 相同(已弃用)语法)。

class PersonClass {
  constructor(fname) {
    this.read = function() {
      console.log('I am reading')
    }
    this.fname = fname;
  }
  speak() {
    console.log('I am speaking');
  }
}
let p1 = new PersonClass('Raj')
console.log(
  PersonClass.prototype.hasOwnProperty('speak'),
  Object.getPrototypeOf(p1) === PersonClass.prototype,
  p1.__proto__ === PersonClass.prototype
);

因此,speak 属性位于实例的内部原型,而不是实例本身。 read 属性是实例的直接属性,就像fname 属性一样。

请记住,类字段语法是 still an experimental proposal(第 3 阶段)。它至少在 Chrome 中实现了,但还不是完全正式的。

【讨论】:

  • 您可能想提一下,类属性仍然只是一个提案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 2012-02-13
  • 2014-11-21
相关资源
最近更新 更多