成员属性、静态属性、私有属性、原型属性

成员属性、静态属性、私有属性、原型属性


  1. 成员属性和成员方法

    在构造函数中,通过 this.属性声明,或者实例化出对象后,通过对象.属性追加的,都属于成员属性或成员方法,也叫实例属性和实例方法。

    function Person(name) {
      this.name = name; // 声明成员属性
      this.say = function () {
        // 声明成员方法
        console.log("haha");
      };
    }
    
    const p = new Preson("p");
    p.age = 18; // 追加成员属性
    console.log(p.say());
  2. 静态属性和静态方法

    通过类名.属性名类名.方法名声明的变量,称为静态属性、静态方法,也叫类属性、类方法,类属性、类方法是属于类的(构造函数的),这类属性或方法必须通过类名.属性调用,而不能通过对象名调用。

    function Person() {}
    Person.age = 21;
    Person.say = function () {
      alert("haha");
    };
    console.log(Person.age, 111); // 21 111
    Person.say(); // haha
    var chaiting = new Person();
    console.log(chaiting.age, 222); // undefined 222
    chaiting.say(); // chaiting.say is not a function
  3. 私有属性和私有方法

    在构造函数中,通过var,let,const声明的属性,称为私有属性,私有属性的作用域仅在当前函数有效,对外不公开,通过对象/类都无法调用到。

    function Person() {
      var sex = "male";
      console.log(sex); // male 私有属性只能在类内使用
    }
    console.log(Person.sex); // undefined 无法调用,私有属性只能在类内使用,且js变量具有函数作用域
    const chaiting = new Person();
    console.log(chaiting.sex); // undefined 无法调用,私有属性只能在类内使用
  4. 原型属性和原型方法

    写在构造函数的 prototype 上,当使用构造函数实例化对象时,该属性方法会进入新对象的 proto 上。

    function Person() {}
    Person.prototype.name = "chaiting"; // 声明原型属性
    Person.prototype.say = function () {
      // 声明原型方法
      console.log("haha");
    };
    const person = new Person();
    console.log(person.name); // chaiting 使用对象调用原型属性
    person.say(); // haha 使用对象调用原型方法