原型
- 每个实例对象(object )都有一个私有属性(称之为__proto__)指向它的原型对象(prototype)。
- 无论什么时候,创建的每个函数都有一个prototype(原型)属性,即原型对象
- 默认情况下,原型对象都会自动获取一个constructor(构造函数)属性,该属性指向prototype属性所在的函数
- prototype(原型)就是通过构造函数来创建的对象实例的原型对象, 这个对象让所有对象实例可以共享它所包含的属性和方法
- 所有普通的[[Prototype]]链最终都会指向内置的Object.prototype
构造函数
- 任何函数,只要通过new操作符来调用,就可以作为构造函数
- 构造函数new一个对象实例的过程
- 创建一个新对象实例;
- 将构造函数的作用域赋给新对象实例
- 执行构造函数中的代码,为新对象实例添加属性
- 返回新对象实例
新对象实例中有一个constructor属性,指向构造函数
function Person() {
this.sayHello = function (params) {
console.log('hello');
};
}
Person.prototype.name = 'person';
const person1 = new Person();
// Person.prototype === person1.__proto__
console.log(JSON.stringify(Person.prototype)); // {"name":"person"}
console.log(JSON.stringify(person1.__proto__)); // {"name":"person"}
console.log(Person.prototype === person1.__proto__); // true
console.log(`getPrototypeOf: ${Object.getPrototypeOf(person1) === Person.prototype}`); // true
console.log(`constructor: ${Person.prototype.constructor === Person}`); // true
console.log(person1.__proto__.constructor === Person.prototype.constructor); // true
console.log(person1.__proto__.constructor === Person); // true
console.log(person1.__proto__.constructor.prototype === Person.prototype); // true
// 对象实例中有一个constructor属性,指向构造函数
console.log(JSON.stringify(person1.constructor === Person))