基础 (六) js 面向对象

使用 class 方式创建对象 以及继承父类

// 类
      class People {
        constructor(name, age) {
          this.name = name;
          this.age = age;
        }
        Say() {
          console.log(this.name + "," + this.age);
        }
      }
      //创建对象
      var user = new People("xx", 12);
      user.Say();


      // 类继承
      class Star extends People {
        constructor(name, age) {
          super(name, age);
        }
        SayHello() {
          super.Say();
        }
      }
      var liu = new Star("liu", 12);
      liu.SayHello();

  

 

 // 利用构造函数创建对象
      var Fruit = function (name, price) {
        this.name = name;
        this.price = price;
        this.ShowPrice = function () {
          console.log(this.name + "." + this.price);
        };
      };

      // fn();
      // 1. call() 可以调用函数
      // fn.call();
      // 2. call() 可以改变这个函数的this指向 此时这个函数的this 就指向了o这个对象

      var Apple = function (name, price) {
     //调用父类的构造函数 Fruit.call(this, name, price); this.ShowApple = function () { console.log(this.name); }; }; Apple.prototype = new Fruit(); //构造函数 重新指向 本对象的构造函数 Apple.prototype.constructor = Apple; var QiXia = new Apple("栖霞苹果", 20); QiXia.ShowApple(); //调用父类方法 QiXia.ShowPrice();

  

// object创建

 var Anmail =new Object();
       Anmail.Name ='动物'
       Anmail.Show=function(){
        console.log(this.Name)
       }
       Anmail.Show()

  

//子面量 创建

  var Anmail ={name:'动物',Show:function(){
        console.log(this.name)
       }}

       Anmail.Show();

  

 

posted on 2024-09-09 14:22  是水饺不是水饺  阅读(17)  评论(0)    收藏  举报

导航