ducky_L

导航

js 如何实现类

一、使用原型

            function Chicken1(name) {
                this.name = name
            }
            Chicken1.prototype.kind = 'chicken';
            Chicken1.prototype.say = function () {
                console.log(`hello,i'm a ${this.kind},my name is ${this.name}`)
            }
            Chicken1.prototype.fly = function () {
                console.log('i can fly')
            }
            const d=new Chicken1('小鸡2');
            d.say() //hello,i'm a chicken,my name is 小鸡2
            d.fly() // 'i can fly

  

二、使用class

         class Chicken{
                #kind='chicken'   //私有属性
                constructor(name){
                    this.name=name;
                }
                say(){
                    console.log(`hello,i'm a ${this.#kind},my name is ${this.name}`)
                }
                fly(){
                    console.log('i can fly')
                }
            }    
        const c=new Chicken('小鸡1');
        c.say() //hello,i'm a chicken,my name is 小鸡1
        c.fly() //i can fly

  

class 几个概念:

静态属性/方法:静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。

class MyClass {
  static myStaticProp = 42;  //静态属性

  constructor() {
    console.log(MyClass.myStaticProp); // 42
  }
}
const a=new MyClass();

a.myStaticProp //undefined   
MyClass.myStaticProp //42

  私有属性/方法:只能在类的内部访问的方法和属性,外部不能访问。ES2022正式为class添加了私有属性,方法是在属性名之前使用#表示。

class IncreasingCounter {
  #count = 0;  //私有属性
  get value() {
    console.log('Getting the current value!');
    return this.#myCount; //不存在myCount 报错
  }
  increment() {
    this.#count++;
  }
}

const counter = new IncreasingCounter();
counter.#count // 实例化对象访问私有属性 报错 说明:浏览器控制台运行不报错,可能是浏览器行为
counter.#myCount //不存在myCount 报错

  共有属性/方法:其他写在类中的就为共有属性/方法

posted on 2023-04-24 17:44  ducky_L  阅读(25)  评论(0编辑  收藏  举报