Javascript JS类:类声明中ES6 myFunc(){..}和ES5 myFunc=function(){..}之间的差异

Javascript JS类:类声明中ES6 myFunc(){..}和ES5 myFunc=function(){..}之间的差异,javascript,es6-class,function-expression,class-fields,Javascript,Es6 Class,Function Expression,Class Fields,在下面的代码中 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=函数{console.log'I

在下面的代码中

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=函数{console.log'I am reading'}成为新创建实例的属性,即

p1.hasOwnProperty“read”为true

与speak相反,{console.log'I am speak';}被分配给PersonClass.prototype。i、 e

p1.hasOwnProperty的“speak”为False

p1.\uuuu proto\uuuu.hasOwnProperty'speak'为真

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

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

我认为speak{…}只是ES6中speak=function{…}的较短语法

谢谢

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.getPrototypeOfp1相同,与p1相同

类人类{ 构造函数名称{ this.read=函数{ 控制台。记录“我正在阅读” } this.fname=fname; } 说{ console.log“我在说话”; } } 设p1=新的人员类“Raj” console.log PersonClass.prototype.hasOwnProperty'speak', Object.getPrototypeOfp1==PersonClass.prototype, p1.uuu proto_uuuu==PersonClass.prototype ;

是新的类字段语法。它实际上与在构造函数中为实例的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.getPrototypeOfp1相同,与p1相同

类人类{ 构造函数名称{ this.read=函数{ 控制台。记录“我正在阅读” } this.fname=fname; } 说{ console.log“我在说话”; } } 设p1=新的人员类“Raj” console.log PersonClass.prototype.hasOwnProperty'speak', Object.getPrototypeOfp1==PersonClass.prototype, p1.uuu proto_uuuu==PersonClass.prototype
;因为js遵循原型继承。不,方法语法不是类属性的缩写。。。类的主体中的语法等效于this.variableName=。。。因为js遵循原型继承。不,方法语法不是类属性的缩写。variableName=。。。类的主体中的语法等效于this.variableName=。。。构造函数中的语句。您可能希望指出类属性仍然只是一个建议。您可能希望指出类属性仍然只是一个建议