【笔记】关于原型

205 阅读2分钟

原型的总结图(晕了就划回来看这里)

image.png

原型的创建与简单使用

使用es6语法写一个构造函数并用它来生成两个实例对象。

//构造函数
class Student {
    /**
     * 生成学生原型
     * (给函数中的形参进行赋值即为该形参的默认值。简单说就是设置默认值!)
     * @param {*} name 名字
     * @param {*} age 年龄
     */
    constructor(name = "小明", age = 23) {
      this.name = name;
      this.age = age;
    }
}
//构造出来的对象
let student1 = new Student();
let student2 = new Student("小张", 25);

console.log(student1, student2);
//打印结果:Student { name: '小明', age: 23 } Student { name: '小张', age: 25 }

原型对象

要获取到原型对象,从该构造函数构造函数实例化出来的对象都能通过途径进行获取。其中构造函数使用prototype获取,构造出来的实例化对象使用__proto__获取。

class Student {
    /**
     * 生成学生原型
     * @param {*} name 名字
     * @param {*} age 年龄
     */
    constructor(name = "小明", age = 23) {
      this.name = name;
      this.age = age;
    }
}
let student1 = new Student();
let student2 = new Student("小张", 25);

console.log(Student.prototype); //{constructor: class Student}
console.log(student1.__proto__); //{constructor: class Student}
console.log(student1.__proto__ === Student.prototype); //true

重点:

class Student {
    /**
     * 生成学生原型
     * @param {*} name 名字
     * @param {*} age 年龄
     */
    constructor(name = "小明", age = 23) {
      this.name = name;
      this.age = age;
    }
}

// 给原型对象设置一个性别属性
Student.prototype.gender = "男";
console.log(Student.prototype);
// 打印结果:{gender: '男', constructor: ƒ}
// 这时gender就会进入到原型对象中去,很正常对吧
let student3 = new Student();
console.log(student3);
// 打印结果:Student {name: '小明', age: 23}
// 这里显然是没有影响到student3的,它并没有gender属性,那打印出来看看
console.log(student3.gender);
// 打印结果:"男"
//神不神奇!这其实是因为我们的实例化对象要取值时,找不到这个属性呀,那怎么办??
//其实这时这个对象就会去它的原型(student3.__proto__)里面去找。
//显然上面打印出来的原型对象中是含有这个gender属性的,所以就会使用这个属性。(注意了,是找不到的时候!)

构造函数的原型对象:

console.log(Student.prototype.__proto__) // {constructor: ƒ Object(), ... } 
//打印结果是Object的原型对象
//继续找这个Objdect的原型对象:
console.log(Student.prototype.__proto__.__proto__) // null
//为null了,意味着这应该就是原型终点了吧...

构造器(constructor)

原型对象的构造器就是我们一开始写的那个构造函数咯!

class Student {
    /**
     * 生成学生原型
     * @param {*} name 名字
     * @param {*} age 年龄
     */
    constructor(name = "小明", age = 23) {
      this.name = name;
      this.age = age;
    }
}
let student1 = new Student();
let student2 = new Student("小张", 25);

console.log(Student.prototype.constructor);
console.log(student1.__proto__.constructor);
//打印结果:
//   class Student {
//     /**
//      * 生成学生原型
//      * @param {*} name 名字
//      * @param {*} age 年龄
//      */
//     constructor(name = "小明", age = 23) {
//       this.name = name;
//       this.age = age;
//     }
//   }

//兜兜转转都还是指的是构造函数
console.log(Student.prototype.constructor === Student); // true
console.log(student1.__proto__.constructor === Student); // true