ES5、ES6自学笔记

类和对象 对象类创建类
class Person {}// 1. 构造函数具有原型对象prototypeconsole.log(Person.prototype);// 2. 构造函数原型对象prototype里面有constructor指向构造函数本身console.log(Person.prototype.constructor);// 3. 构造函数可以通过原型对象添加方法Person.prototype.eat = function () {console.log('hello');}// 4. 构造函数创建的实例对象有__proto__对象原型指向构造函数的原型对象var xy = new Person;xy.eat();// console输出helloconsole.log(xy.__proto__);
和super关键字
类的继承通过关键字实现,子类通过 super 方法获得父类属性 。
语法:
class { // 父类}
class Son{ // 子类继承父类}
super(x, y) 直接使用父类的构造函数
super.方法名() 在子类中调用父类的方法
// 类的继承// 类的继承通过 extends 关键字实现,子类通过 super 方法获得父类属性 。class Father{constructor(name, age){this.name = name;this.age = age;}money(){console.log(100);}}class Son extends Father{constructor(name, age, sex){// 使用super关键字获取父类的构造方法super(name, age);this.sex = sex;}// 在子类中直接声明一个与父类同名函数即可进行重写money(){console.log(10);}// 创建子类独有的方法game(){console.log("我在打游戏");}}var son = new Son("demo", 19, "男");// 使用子类独有的方法son.game();// 因为是继承,所以Son可以直接调用Father的money方法,如果后面我们不重写父类的方法,会打印100;但是后面我们又将方法重写了,所以打印的是10son.money();
注意:
在 ES6 中类没有变量提升,所以必须先定义类,才能通过类实例化对象.类里面的共有属性和方法一定要加this使用.类里面的this指向问题. 里面的this指向实例对象, 方法里面的this 指向这个方法的调用者
class Father1 {constructor(x, y) {this.x = x;this.y = y;}sum() {console.log(this.x + this.y);}}class Son1 extends Father1{constructor(x, y) {// 利用super 调用父类的构造函数,并且给自己的x, y赋值// super 必须在子类this之前调用super(x, y);this.x = x;this.y = y;}sub(){console.log(this.x - this.y);}}var son1 = new Son1(10, 1);son1.sum();// 调用父类的sumson1.sub();// 使用自己的sub
类里的this指向问题
>var name = "ljy";var value = "http://www.kingceram.com/post/lv";var that, _that;class Star {constructor(value) {// 将实例赋值给that,以方便获取name,并且赋值要放在方法的前面_that = this;// constructor 里面的this 指向的是 创建的实例对象this.name = value;// 不使用this则是直接指向全局变量console.log(value);// 形参也叫value,所以输出形参console.log(name);// ljyconsole.log(this.name);// 刘德华// 想让函数一构造就使用sing方法this.sing();// 给按钮绑定事件this.btn = document.querySelector("button");this.btn.onclick = this.sing;}sing() {// 由于这里的this指向的方法的调用者,所以给按钮绑定这个方法则指向按钮,但是按钮又没有name值,所以我们可以在构建对象的时候将this赋值给其他的变量(_that),然后再从_that里面获取name的值// console.log(this.name);console.log(_that.name);}dance() {// 这里的this指向的是调用的对象that = this;}}var ldh = new Star("刘德华");// 先调用dance方法,将this赋值给that,然后进行对比ldh.dance();// 这里的that绝对等于ldh,因为是ldh调用了dance()console.log(that === ldh);
构造函数和原型 构造函数
// 1. 利用 new Object() 创建对象var obj1 = new Object();// 2. 利用 对象字面量创建对象var obj2 = {};// 3. 利用构造函数创建对象function Star(uname, age) {this.uname = uname;this.age = age;this.sing = function() {console.log('我会唱歌');}}var ldh = new Star('刘德华', 18);var zxy = new Star('张学友', 19);console.log(ldh);ldh.sing();zxy.sing();