自学内容网 自学内容网

js: public、private、protected 定义和区别

public、private、protected是一些关键字,用于定义类中的属性和方法的访问权限

public:是默认的访问修饰符,表示属性或方法可以在类的内部和外部被访问。这意味着可以在类的实例化对象中直接访问该属性或方法,也可以通过类的实例化对象的引用访问。

class Person {
  public name: string = 'xiaoming';
  public sayHello() {
    console.log('Hello', this.name);
  }
}

class Student extends Person {
  public introduce() {
    console.log('i am' + this.name);
  }
}

const per = new Person();

console.log(per.name); // xiaoming
console.log(per.sayHello()); // Hello xiaoming

const stu = new Student();
console.log(stu.name); // xiaoming
console.log(stu.sayHello()); // Hello xiaoming
console.log(stu.introduce()); // i am xiaoming

private:是私有的访问修饰符,表示属性或方法只能在类的内部被访问。这意味着不能在类的实例化对象中直接访问该属性或方法,也不能通过类的实例化对象的引用访问。私有属性和方法通常用于隐藏类的内部实现细节,只允许通过公共方法来访问。

class Person {
  private name: string = 'xiaoming';
  public sayHello() {
    console.log('Hello', this.name);
  }
}

class Student extends Person {
  public introduce() {
    console.log('i am' + this.name);
  }
}

const per = new Person();

console.log(per.name); // 外部不能访问private属性和方法
console.log(per.sayHello()); // 通过公共方法能访问private属性和方法

const stu = new Student();
console.log(stu.name); // 子类不能访问父类private属性和方法
console.log(stu.sayHello()); // Hello xiaoming
console.log(stu.introduce()); // 子类内外部都不能访问父类的private属性和方法

protected:是受保护的访问修饰符,表示属性或方法可以在类的内部和子类的内部中被访问。这意味着可以在类的实例化对象中直接访问该属性或方法,也可以通过子类的实例化对象的引用访问。受保护的属性和方法通常用于定义类的内部状态,只允许类的子类访问。


class Person {
  protected name: string = 'xiaoming';
  public sayHello() {
    console.log('Hello', this.name);
  }
}

class Student extends Person {
  public introduce() {
    console.log('i am' + this.name);
  }
}

const per = new Person();

console.log(per.name); // 外部不能访问protected属性和方法
console.log(per.sayHello()); // 通过公共方法能访问protected属性和方法

const stu = new Student();
console.log(stu.name); // 子类外部不能访问父类protected属性和方法
console.log(stu.sayHello()); // Hello xiaoming
console.log(stu.introduce()); // i am xiaoming 子类内部方法都访问父类的protected属性和方法


原文地址:https://blog.csdn.net/weixin_44384273/article/details/142815209

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!