构造函数

构造函数和普通函数形式一样,区别在于使用的方式。

  1. function Animal(name) {
  2. this.name = name;
  3. this.subname = name;
  4. this.arr = [1, 2, 3];
  5. this.eat = '吃肉';
  6. }
  7. Animal.prototype.address = {
  8. location: '山里'
  9. }
  10. let mouse = new Animal('老鼠');
  11. let tiger = new Animal('老虎');

通过 new 操作符实例化一个对象,构造函数中的 this 会指向这个新创建的对象,并且单独为其创建属性。还会将这个对象的 proto 属性指向构造函数的原型对象。

proto属性

实例化的对象有一个 proto 属性执行构造函数的原型对象。当无法找到实例对象上的属性时,会去原型对象中去找。

  1. console.log(mouse.arr === tiger.arr);//false
  2. console.log(mouse.address === tiger.address);//true
  3. console.log(mouse.__proto__ === Animal.prototype);//true
  4. console.log(tiger.__proto__ === Animal.prototype);//true

constructor

实例化的对象会有一个 constructor 属性指向构造函数。

  1. console.group(mouse.constructor === Animal);//true

实现继承

call + setPrototypeOf

通过父类上的 call 方法给父类传参,然后通过 proto 属性或者通过 setPrototypeOf 方法将子类的原型指向父类的原型对象。

  1. function Monkey(name) {
  2. this.name = name;
  3. this.age = 10;
  4. Animal.call(this, ...arguments);
  5. }
  6. Monkey.prototype.__proto__ = Animal.prototype;
  7. // 等同于
  8. //Object.setPrototypeOf(Monkey.prototype, Animal.prototype);
  9. const m1 = new Monkey();
  10. console.log(m1.address); //{ location: '山里' }
  11. console.log(m1.eat);//吃肉
  12. console.log(m1.subname);//猴子
  13. console.log(m1.constructor)//[Function: Monkey]

call + Object.create

同样通过 call 给父类传参,然后使用create方法将Monkey的原型对象指向 以Animal的原型对象为原型的新对象,但是需要注意的是需要将构造函数指向Monkey,不然指向的就是 Animal。

  1. function Monkey(name) {
  2. this.name = name;
  3. this.age = 10;
  4. Animal.call(this, ...arguments);
  5. }
  6. Monkey.prototype = Object.create(Animal.prototype, { constructor: { value: Monkey } });
  7. const m1 = new Monkey('猴子');
  8. console.log(m1.address);// { location: '山里' }
  9. console.log(m1.eat);//吃肉
  10. console.log(m1.subname);//猴子*/
  11. console.log(m1.constructor);//[Function: Monkey]

原型继承

不太常用,一样的用call,同时也需要用修改Object.defineProperty 修改实例 constructor,很是麻烦,每次都要修改。

  1. function Monkey(name) {
  2. this.name = name;
  3. this.age = 10;
  4. Animal.call(this,...arguments)
  5. }
  6. Monkey.prototype = new Animal();
  7. const m1 = new Monkey('猴子');
  8. Object.defineProperty(m1, 'constructor', {
  9. value:Monkey
  10. })
  11. console.log(m1.address);// { location: '山里' }
  12. console.log(m1.eat);//吃肉
  13. console.log(m1.subname);//猴子
  14. console.log(m1.constructor);//[Function: Monkey]

拷贝继承

更加鸡肋。。。仅适用用特殊场合。