Javascript-ES6方法定义速记仅创建一个功能对象吗?

使用在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 Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
    }
    name () {
        return this.make + this.model;
    }
}

这只会创建一个共享功能对象吗?还是在每个新电话(例如第一个电话)上实例一个新电话?

解决方法:

您将为每个实例创建在构造函数中定义为属性的函数.您在外部构造函数中定义的函数将在该原型上可用.因此,名称functon将仅创建一次.

说这是你的课

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()
上一篇:java-为什么对象的状态可以是植根于该对象的对象图中字段的子集?


下一篇:数据库模式的C类设计