【问题标题】:Does the ES6 Method Definition Shorthand only create one function object?ES6 方法定义简写是否只创建一个函数对象?
【发布时间】:2019-10-23 21:12:33
【问题描述】:

使用在 JavaScript 中创建类的“旧方式”,您通常会避免做这样的事情:

function Car {
    this.make = "Renault";
    this.model = "Twingo";
    this.name = function () {
        return this.make + this.model;
    };
}

因为它会在类的每个实例化时创建一个新的函数对象,所以你宁愿这样做:

function Car {
    this.make = "Renault";
    this.model = "Twingo";
}

Car.prototype.name = function() {
    return this.make + this.model;
}

在 ES6 中,使用较新的 class 语法,我们可以执行以下操作:

class Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
    }
    name () {
        return this.make + this.model;
    }
}

这是否只创建一个共享函数对象?或者它是否像第一个一样在每个new 调用中实例化一个新的?

【问题讨论】:

  • “在 ES6 中,我们有这样的语法来定义一个方法:”不,这看起来不正确。但是之后的class sn-p 只创建了一个函数并将其放在原型上,是的。 (您可以通过'name' in Car.prototype查看。)
  • 该语法在对象字面量(显然每个对象只有一个函数,因为只有一个对象)和类(原型上的一个函数,无论创建多少对象)中都是有效的.它在您展示的功能中无效。
  • 该链接在对象文字中显示它,而不是在函数中。 const car = { make: "Renault", model: "Twingo", name ( ) { return this.make + this.model } }; 有效,但它创建的是单个对象,而不是类或构造函数。 name ( ) { return this.make + this.model } 本身在类定义或对象字面量之外无效。
  • Ry 是正确的。它在Car.prototype 上创建一个函数,该函数将由 Car 实例共享。这很容易检查。 const car1 = new Car; const car2 = new Car; console.log( car1.name === car2.name );
  • @OndraŽižka:已经是 JavaScript 了……

标签: javascript oop object


【解决方案1】:

您在构造函数中定义为属性的函数将为每个实例创建。您在构造函数外部定义的函数将在原型上可用。所以名称函数只会被创建一次。

说这是你的课

class Test {
  constructor(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.func1 = function() {};
  }
  func2() {}
}

const test = new Test('one','two');

如果您签入 devtools,您会看到 func1 可用于每个实例,但 func2 可用于原型。

Test {prop1: "one", prop2: "two", func1: ƒ}
  func1: ƒ ()
  prop1: "one"
  prop2: "two"
  __proto__:
    constructor: class Test
    func2: ƒ func2()

【讨论】:

  • 请用粘贴的代码替换屏幕截图。这是 StackOverflow 上一个非常重要的实践,以提高可搜索性。
猜你喜欢
  • 2020-06-09
  • 2011-02-27
  • 2023-03-27
  • 2019-02-06
  • 2021-03-28
  • 2019-03-13
  • 2022-01-17
  • 1970-01-01
  • 2016-10-05
相关资源
最近更新 更多