类定义与构造函数
在JavaScript中,类的定义可以通过class关键字来实现,也可以通过传统的构造函数和原型链的方式来实现。上述代码展示了这两种不同的实现方式。
使用class关键字
class Example {constructor(name) {this.name = name;}func() {console.log(this.name);}
}
-  class Example定义了一个名为Example的类。
-  constructor(name)是类的构造函数,用于初始化新创建的对象。当使用new Example(name)创建实例时,这个构造函数会被调用。
-  func()是一个实例方法,定义在类的原型上,所有实例都可以调用这个方法。
使用构造函数和原型链
'use strict';
function Example(name) {if (!new.target) {throw new TypeError(`Class constructor Example cannot be invoked without 'new'`);}this.name = name;
}Object.defineProperty(Example.prototype, 'func', {value: function () {if (new.target) {throw new TypeError(`Example.prototype.func is not a constructor`);}console.log(this.name);},enumerable: false,
});
-  'use strict';启用严格模式,确保代码执行时的一些错误会被抛出。
-  function Example(name)定义了一个构造函数。通过检查new.target,确保这个函数只能通过new关键字调用,否则抛出错误。
-  Object.defineProperty(Example.prototype, 'func', {...})定义了一个不可枚举的实例方法func。这个方法通过检查new.target,确保它不能被当作构造函数使用。