• 类的构成:属性和方法

ES5 继承

// 父
function Person(name) {
  this.name = name;
  this.say = function () {
    return this.name;
  };
}
Person.prototype.ss = function () {
  console.log("ss");
};
// 子
function Per(name) {
  Person.call(this, name);
  this.age = 12;
}
Per.prototype.constructor = Per;
Per.prototype = new Person();
const p = new Per("cz");
console.log(p); // { name: 'cz', age: 12, say: function }
console.log(p.__proto__); // { name: undefined, say: function, ss: function }

缺陷:

  • 调用了两次 Person
  • 私有属性和原型上都有 name,say

Object.create

let obj = {
    a: 1,
    b: 2,
    o: {
      a: 1,
      b: 2
    },
    say() {
        return 'say'
    }
}
let obj2 = Object.create(obj)
obj2.say = function() {
    return 'say2'
}
console.log(obj2.say()) // say2
console.log(obj.say()) // say

obj2.o.a = 2;
obj.o.a // 2
所以:obj和obj2的下面的对象指向都是一样的

思考:ES5,JS的继承都有这个问题,如何解决?
Object原型上被第三方插入了属性name,如何让创建的对象访问不到name

1. let o = Object.create(null) // {},没有原型的对象
2. let o = {}
   Object. defineProperty(o, ‘name’, {
     get() {
       return undefined
     }
   })
3. ?

Class

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  say() {
    return this.name;
  }
}

class Children extends Person {
  constructor(name, age) {
    super(name, age); // 跟ES5继承的 Person.call(this, name, age)类似
  }
  say() {
    return super.say(); // 执行父级的say函数
  }
}

let c = new Children("cz", 18);

console.log(c);

// super是类里的特殊语法
// 不可被输出