为什么在新实例上调用方法?

why is method called upon new instance?

c1.rand 被调用时,我不清楚解释器是如何访问 this.num 的,因为尚未调用构造函数。它不应该在 rand 中调用 constructor() 来设置 this.num 的值吗?

class C {
    constructor() {
        this.num = Math.random();
    }
    rand() {
        console.log( "Random: " + this.num );
    }
}

var c1 = new C();
c1.rand(); // "Random: 0.4324299..." (any number from 0 to 1)

When c1.rand is called I'm not clear how the interpreter is able to access this.num because the constructor function hasn't been called yet.

是的,它有。你写的时候调用了构造函数

var c1 = new C();

Is only the constructor function called b/c constructor is a special keyword?

是的,如果 class 定义了 constructor 函数,当您使用 new 关键字调用 class 时,它将被调用。

constructor 属性 也可以通过实例的原型访问。

var c1 = new C();
c1.constructor === C //=> true

创建对象时会立即调用构造函数,因此当您调用时:

var c1 = new C();

调用了构造函数。名称构造函数来自使用,它会立即被调用,因为 它构造了对象。 这意味着它初始化变量等 - 对象必不可少的东西,在你的情况下 this.num .是的,当声明 class 时,它是对象创建的保留函数。

new 关键字表示 'new instance' 并在创建新实例时调用构造函数。