1. Prototype object: When any function is created, the system will automatically create the corresponding object, called the prototype object
2. The role of the prototype object: solve the memory waste of the constructor + variable pollution
3. The relationship between constructors, prototype objects, and instance objects
- prototype: belongs to the constructor, pointing to the prototype object
- * Solve constructor memory waste + variable pollution
- __proto__: belongs to the instance object, pointing to the prototype object
- * Let the instance object directly access the members of the prototype
- constructor: belongs to the prototype object, pointing to the constructor
- * Allows the instance object to know which constructor it was created by
//1.构造函数
function createP (name, age, sex) {
this.name = name
this.age = age
this.sex = sex
}
//2.原型对象
console.log(createP.prototype);
//给原型对象添加方法
createP.prototype.eat = function () {
console.log('吃东西')
}
createP.prototype.learn = function () {
console.log('学习')
}
//3.实例对象
let p1 = new createP('张三', 20, '男')
let p2 = new createP('李四', 22, '男')
// console.log(p1, p2);
//实例对象可以直接调用原型对象里的方法
p1.eat()
p2.learn()