Prototype, prototype chain
1. The concept of prototype
All JavaScript objects contain a [proto] internal property, which corresponds to its own prototype.
In addition to the prototype [proto], JavaScript function objects also have prototype properties. When the function object is used as a constructor to create an instance, the prototype property value will be used as the prototype [proto] of the instance object.
Every object has a special property called prototype, and the properties and methods defined on the prototype will be shared by every instance object.
//原型的代码理解
let zhangsan=new Person()
let lisi=new Person()
console.log(zhangsan.name) //undefind
console.log(lisi.name)//undefind
zhangsan.name='张三'//给张三改变值
zhangsan.name//张三
lisi.name//undefind
Person.prototype.name='王五'
lisi.name//王五
zhangsan.name//张三 (没有变是因为它是实例化属性)
delete zhangsan.name//把它删了
zhangsan.name//王五
zhangsan.children//[](是一个数组)
zhangsan.children.push('崔鑫琦')//1 (添加一个)
zhangsan.children//['崔鑫琦']
lisi.children//['崔鑫琦']
lisi.children.push('小琦')//2(添加一个)
lisi.children//['崔鑫琦','小琦']
zhangsan.children//['崔鑫琦','小琦']
var wangwu=new Perosn//undefind
wangwu.children//['崔鑫琦','小琦']
Person.prototype.sayName=function(){
//在原型上创建了一个方法
console.log('我叫小崔')
}
wangwu.sayName()//我叫小崔
zhangsan.sayName()//我叫小崔
Second, the concept of the prototype chain
When accessing the properties of an object, first look up in the basic properties, if not, then look up along the __proto__ chain, which is the prototype chain.
Explanation:
When an object calls a property/method that does not exist in itself, it will go to its [proto] associated predecessor prototype object, if not found, it will go to the prototype prototype v=['proto] associated predecessor prototype Go find it. And so on, until you find a property/method or undefined. Thus formed the so-called "prototype chain."