ES6-面向对象

1、区别

  • es5(js)中没有一个类的概念,只有构造方法
    在es6中 js模拟了其他语言实现类的概念,让对象可以由类来产生
    es6 虽然有了类,但是底层实现上 还是以原型对象的拷贝来实例化对象

  • 1、声明

ES5声明类

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};

let p = new Point(3, 4);

ES6声明类

class Point {
    //从底层上来讲,在类里面定义的属性和方法,都是之前的原型属性和方法
    // 构造函数
    //需要传参的属性,写到构造函数里面
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    // 原型函数
    toString = function () {
        return '(' + this.x + ', ' + this.y + ')';
    };
}
  • 2、继承

js继承

  • 1、原型继承

1、子类.prototype = new 父类();
子类.prototype.constructor = 子类

2、子类.prototype = 父类.prototype;
子类.prototype.constructor = 子类

  • 2、构造函数继承

父类在子类中使用 父类.call/apply(this,....)
call()
apply() 参数是一个数组

es6继承 (extends)

class Man extends Person{
    sex = '男';
}

在类中使用自身的属性和方法,用this来使用

  • this.属性
    this.方法()

在子类中要使用父类的属性和方法 ,只能用super

  • super.方法()
  • 只有一种情况例外
    super如果在子类的constructor中,代表着 父类的 constructor

static 修饰一个类属性或类方法

  • 只有类能使用的属性和方法,只能通过类名调用
class Man{
    static a = 123;
    static says(){
        console.log(789789789789);
    }
}

console.log(Man.a);  // 123
Man.says(); 

私有/公有

class Person{
    constructor(){
        this.money = 5678; // 公有
        var money1 = 789789; // 私有
    }
    
    // money = 34567; //公有
    //私有属性
    _money = 789;
    // set  get
    set m1(m){
        this._money = m + 10000;
    }

    get m1(){
        return this._money;
    }
}

var p1 = new Person();
console.log(p1.money);
console.log(p1.m1); //789,一开始设置的那个值
p1.m1 = 5000;
console.log(p1.m1);  // 15000

总结

  • 1、class :定义类的关键字
  • 2、 extends : 子类继承父类 (定义子类时使用)
  • 3、constructor : 构造函数(需要传参的属性,写到构造函数里面)
  • 4、static : 定义类属性, 只有类能使用的属性和方法,只能通过类名调用
  • 5、super : 如果放在子类的构造函数中,直接代表 父类的构造函数
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容