为什么随机 class 的构造函数等于本机 Function 对象?
Why the constructor of a random class equals the native Function object?
为什么下面的代码returns true
?
class MyClass {
constructor(a, b) { }
}
console.log(MyClass.constructor === Function);
根据这个问题: 一个 class
是一个 function
,它在运行时被 constructor
的主体填充,这可以解释上面的行为,但我还是不太明白。有人可以解释吗?
任何类型的 JavaScript 对象的 constructor
属性 实际上是用来构造它的:
一个class
实际上是一个function
,所以它是由Function
构造的。这就是为什么 MyClass.constructor === Function
class
的 constructor
实际上是 class
本身。它也位于 MyClass.prototype.constructor
以使其在实例的 constructor
属性 可用。的确,MyClass === MyClass.prototype.constructor
构造函数只是一个函数,用于创建自定义对象类型并使用new
关键字创建对象的实例。
/**
* `Constructor function` that defines custom data object, commonly named using capital letter.
* The properties will be available for every object created from this function,
* because `this` points to the instance of the object.
*/
function Human(name, lastName) {
this.name = name;
this.lastName = name;
}
/**
* Objects are created from `constructor function` using `new` keyword.
* Parameters that are passed to the function will be the values of object's properties.
*/
const american = new Human('Mike', 'Brown');
在 类 内部,constructor
方法实际上是构造函数 - 创建对象的实例。
class AnotherHuman{
constructor(name, age){
this.name = name;
this.age = age;
}
const student = AnotherHuman('Jack', 22);
为什么下面的代码returns true
?
class MyClass {
constructor(a, b) { }
}
console.log(MyClass.constructor === Function);
根据这个问题:class
是一个 function
,它在运行时被 constructor
的主体填充,这可以解释上面的行为,但我还是不太明白。有人可以解释吗?
任何类型的 JavaScript 对象的 constructor
属性 实际上是用来构造它的:
一个class
实际上是一个function
,所以它是由Function
构造的。这就是为什么 MyClass.constructor === Function
class
的 constructor
实际上是 class
本身。它也位于 MyClass.prototype.constructor
以使其在实例的 constructor
属性 可用。的确,MyClass === MyClass.prototype.constructor
构造函数只是一个函数,用于创建自定义对象类型并使用new
关键字创建对象的实例。
/**
* `Constructor function` that defines custom data object, commonly named using capital letter.
* The properties will be available for every object created from this function,
* because `this` points to the instance of the object.
*/
function Human(name, lastName) {
this.name = name;
this.lastName = name;
}
/**
* Objects are created from `constructor function` using `new` keyword.
* Parameters that are passed to the function will be the values of object's properties.
*/
const american = new Human('Mike', 'Brown');
在 类 内部,constructor
方法实际上是构造函数 - 创建对象的实例。
class AnotherHuman{
constructor(name, age){
this.name = name;
this.age = age;
}
const student = AnotherHuman('Jack', 22);