class类的创建和对象方法的继承

一.类的创建及其方法和属性的调用

代码实例:


class Star {
            constructor(uname, age) {
          //此时的this指向实例化对象
this.uname = uname, this.age = age } sing(song) { console.log(this.uname + song); } } var ldh = new Star('刘德华', 54); var zxy = new Star('张学友', 56); console.log(ldh); console.log(zxy); ldh.sing('冰雨')

注意事项:

  • 通过class关键字创建类,类名首字母大写;
  • 类里面的constructor函数,可以接受传递过来的参数,同时返回实例对象;
  • constructor函数只要new生成实例是,就会自动调用这个函数;
  • es6中没有变量的提升,必须先定义类,再实例化对象.

二.类的继承

(1)extends的继承

class Father {
            constructor() {}
            money() {
                console.log(100);
            }
        }
class Son extends Father {}
var son = new Son();
son.money();//100

class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y
            }
            sum() {
                console.log(this.x + this.y);
            }
        }
        class Son extends Father {
            constructor(x, y) {
                //此时,super关键字必须放置this之前
                super(x, y)
                this.x = x;
                this.y = y;
            }
            subtract() {
                console.log(this.x - this.y);
            };
        }
        var son = new Son(11, 2);
        son.subtract();//9
        son.sum();//13

 

 

 

posted @ 2020-07-13 17:38  流弊的小涛  阅读(117)  评论(0编辑  收藏  举报