JavaScript对象中不同的函数声明有什么区别(如果有的话)?

5

我有一个JavaScript对象:

var methods = {

  classStyle() {
    console.log('Class style function');
  },

  traditionalStyle: function() {
    console.log('Traditional style function');
  },

  arrowStyle: () => {
    console.log('Arrow style function');
  }

};

methods.classStyle();
methods.traditionalStyle();
methods.arrowStyle();

输出结果符合预期:
(index):70 Class style function
(index):74 Traditional style function
(index):78 Arrow style function

我的问题是:

  1. 这些不同声明方法之间有什么区别吗?
  2. 是个人偏好的问题吗?还是内部机制会改变?
  3. 在使用不同风格时需要考虑哪些因素?

请查看此链接那个链接 - Bergi
请至少阅读一些关于箭头函数的内容。它与其他两种函数确实有所不同。 - jfriend00
3个回答

5
“类样式函数”(简写法)与普通函数非常相似。唯一的区别在于,“类样式函数”不能用作构造函数(即使用new调用),因此它没有prototype 属性。至于箭头函数,请参见箭头函数与函数声明/表达式:它们是否等效/可交换?。简而言之,箭头函数不绑定它们自己的thisarguments,也不能与new一起使用。

这是基于个人喜好吗?还是内部机制有所改变?

在ES6+中,在对象中使用传统的函数语法没有必要,因为简写方法语法更简单更安全,因为如果你不小心尝试将方法用作构造函数,你会得到一个错误。至于箭头函数,只能在您不需要使用this访问对象时使用。

@maerics 不是的,因为 this 与箭头函数非常不同,它们实际上是三个不同的东西。 - Bergi
“class-style”也可以使用super.foo,而函数表达式则不行,箭头函数的使用取决于父级作用域是否允许super.foo - loganfsmyth
@loganfsmyth 它有实际的应用吗?一个普通对象本来就没有父类,除非你使用 Object.setPrototypeOf() 手动设置。 - Michał Perłakowski
你当然可以使用 __proto__ 声明一个对象文字。不管哪种方式,对象最终都会有一个父级,super.foo 也能正常工作。这可能并不常见,但它确实是一种区别。 - loganfsmyth

1

arrowStyle由于箭头函数的差异而不同。请参见下面有关this的差异:

var methods = {

  classStyle() {
    console.log('class this is', this);
  },

  traditionalStyle: function() {
    console.log('traditional this is', this);
  },

  arrowStyle: () => {
    console.log('arrow this is', this);
  }

};

methods.classStyle.call(5);
methods.traditionalStyle.call(5);
methods.arrowStyle.call(5);


还请查看@Michał Perłakowski发布的链接。 - AnilRedshift

1

作为补充,正如所提到的,第一和第二个不同。一个主要的区别是它们在哪里以及如何使用。看看这个片段,你会发现当对象被创建时,方法定义是可用的,但函数声明却不是。

这意味着当你使用传统风格定义时,你不能在对象的其他地方使用它,它将变成未定义的。而使用类风格则会有所不同,这是一个巨大的区别。

methods = {
  classStyle() {

    //console.log('class this is', this);
    return 'class';
  },

  traditionalStyle: function() {
    //console.log('traditional this is', this);
    return 'tradition';

  },

  arrowStyle: () => {
    console.log('arrow this is', this);
  },

  testFn() {
    console.log('class is', this.classStyle);
    console.log('traditionnal is', this.traditionnalStyle);
  },

  get classProp() {
    return this.classStyle();
  },

  get traditionnalProp() {
    return this.traditionnalStyle();
  }

};



methods.testFn();
console.log(methods.classProp);
console.log(methods.traditionnalProp);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接