什么是原型
- 所有
引用类型
都有一个__proto__ (隐式原型)
属性,属性值是一个普通对象 - 所有
函数
都有一个prototype(显式原型)
属性,属性值是一个普通对象 - 所有引用类型的
__proto__
都指向他的构造函数的prototype
example
function Father(name) {
this.name = name
}
let Son = new Father('小头爸爸')
console.log(Son.__proto__ === FAther.prototype) // true
console.dir('Son': Son)
console.dir('Father': Father)
复制代码
echo
Son: Father {
name: '小头爸爸',
__proto__ : Object
}
Father: Father () {
name: '小头爸爸',
prototype:{...}
__proto__: ƒ (...)
}
复制代码
什么是原型链
当访问某个对象的属性时,会现在这个对象本身属性上查找,如果没有找到,就去他的__proto__ 查找,既他的构造函数的prototype查找,如果没有找到,就去他的构造函数的prototype.__proto 查找。这样一层一层的查找就会形成一个链式的结构,这就是原型链
- 一直往上层查找,直到找到null还没有找到,则返回undefined
- Object.prototype.proto = null
- 所有从原型或更高级原型中的得到、执行的方法,其中的this在执行时,指向当前这个触发事件执行的对象
原型的作用
共享方法
实战
按照如下要求实现Person 和 Student 对象
- Student 继承Person
- Person 包含一个实例变量 name, 包含一个方法 printName
- Student 包含一个实例变量 score, 包含一个实例方法printScore
- 所有Person和Student对象之间共享一个方法
function Person(name) {
this.name = name
this.printNama = function () {
console.log('Person printNama ');
}
}
Person.prototype.commen = function () {
console.log('commenMethods')
}
function Student(name, score) {
Person.call(this, name)
this.score = score
this.printScore = function () {
console.log('Student printScore');
}
}
Student.prototype = new Person()
let person = new Person('小红', 30)
let student = new Student('小敏', 20)
console.log(Student.commen === Person.commen)
console.log('student', student)
console.log('person', person)
复制代码
参考文章
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END