functionMyClass(){// 在这里我们可以添加初始化代码} 1. 2. 3. 解释: function MyClass() { ... }: 这是一个函数定义,MyClass是构造函数的名字。 2. 在构造函数中定义公共方法 我们可以在构造函数中定义一个公共方法publicMethod,使得它在实例化后可以被调用。 functionMyClass(){this.publicMethod=functi...
side);}getarea(){// Getter方法returnthis.width*this.height;}setarea(value){// Setter方法this.width=Math.sqrt(value);this.height=Math.sqrt(value);}#privateMethod(){// 私有方法console.log('
classUser{static#MAX_INSTANCES=2;static#instances=0;name;constructor(name){User.#instances++;if(User.#instances>User.#MAX_INSTANCES){thrownewError('Unable to create User instance');}this.name=name;}}newUser('张三');newUser('李四');newUser('王五');// throws Error 静态字段User.#MAX_INSTA...
Class.method这种模式定义的method是绑定在Class对象之上的。在js中,我们知道一切皆为对象,包括Class(本质上是一个function)。当我们以ClassFunction.method方式定一个一个method时就是在function对象上定义了一个属性而已。这个Class.method和通过new Class()生成的instance没有任何关系,我们可以认为这种Class.method形式为...
public:该字段可以在任何地方访问 private:字段只能在类的主体中访问 3.1 公共实例字段 让我们再次看看前面的代码片段: classUser{constructor(name) {this.name= name; } } 表达式this.name = name创建一个实例字段名,并为其分配一个初始值。然后,可以使用属性访问器访问name字段 ...
returnthis.publicFieldName+this.#privateFieldName; } } 其中,this.#可以简化,去掉 this 也没问题,下面两种写法是等价的: method() { #privateFieldName; } method() { this.#privateFieldName; } 在Class 定义中引用 Class 实例的私有属性 对于私有属性,我们是不可以直接通过 Class 实例来引用的,这也是私有...
24 //alert(publicName1); 25 //alert(publicName2); 26 // 无法访问静态属性 27 //alert(staticName); 28 29 //可以访问私有方法 30 alert(privateMethod()); 31 alert(windowMethod()); 32 // 无法访问公有方法 33 //alert(publicMethod1()); ...
public:该字段可以在任何地方访问 private:字段只能在类的主体中访问 3.1 公共实例字段 让我们再次看看前面的代码片段: class User {constructor(name) {this.name = name;}} 表达式this.name = name创建一个实例字段名,并为其分配一个初始值。然后,可以...
class Foo { publicFieldName = 1; #privateFieldName = 2; add() { return this.publicFieldName + this.#privateFieldName; } } 其中,this.#可以简化,去掉 this 也没问题,下面两种写法是等价的: method() { #privateFieldName; } method() { ...
publicFieldName + this.#privateFieldName; } } 其中,this.#可以简化,去掉 this 也没问题,下面两种写法是等价的: method() { #privateFieldName; } method() { this.#privateFieldName; } 在Class 定义中引用 Class 实例的私有属性 对于私有属性,我们是不可以直接通过 Class 实例来引用的,这也是私有属性...