概念
1.原型對(duì)象(prototype) 只有函數(shù)有原型對(duì)象 相當(dāng)于每個(gè)函數(shù)具有一個(gè)prototype屬性忽媒,所指向的對(duì)象争拐,就叫原型對(duì)象
2.原型鏈由對(duì)象的proto 繼承連接下來,對(duì)象的proto指向其構(gòu)造函數(shù)的原型對(duì)象晦雨,其中對(duì)象包括普通對(duì)象和函數(shù)對(duì)象
實(shí)例詳解
function Car() {
}
var car = new Car();
console.log(car.__proto__ === Car.prototype);//car 是非函數(shù)對(duì)象 只有__proto__屬性
console.log(car.__proto__.__proto__ === Object.prototype)//car.__proto__.__proto__ = Car.prototype.__proto__ = Object.prototype
console.log(car.__proto__.prototype) //undefined
//總結(jié)的普通對(duì)象的__proto__最終都指向Object.prototype,普通對(duì)象沒有prototype
console.log(Car.prototype)// {constructor:function(){ }}
console.log(Car.prototype.prototype)//undefined
console.log(Car.prototype.__proto__ === Object.prototype)//Object.prototype
console.log(Car.__proto__ ===Function.prototype)//
console.log(Car.__proto__.__proto__)
//所有函數(shù)對(duì)象都有原型對(duì)象 所有函數(shù)對(duì)象的(一級(jí))__proto__指向Function.prototype(空函數(shù)) 最終指向Object.prototype
console.log(Function.prototype === Function.__proto__);//true
console.log(Function.prototype === Object.__proto__)//true
總結(jié)
所有普通對(duì)象的的最終proto 都指向Object.prototype
所有函數(shù)對(duì)象的一級(jí)proto 都指向Function.prototype(空函數(shù)) 最終proto還是指向Object.prototype
所有函數(shù)對(duì)象都有prototype架曹,他們的原型對(duì)象proto最終都指向Object.proto,沒有prototype對(duì)象,原型對(duì)象都有constructor屬性 指向構(gòu)造函數(shù)本身闹瞧。函數(shù)對(duì)象包括 Function Object,Array绑雄,Date等函數(shù)。
繼承
ES5
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
console.log(this.name);
}
function Student(name){
Person.call(this,name);
}
var __proto = Object.create(Person.prototype);
__proto.constructor = Student;
Student.prototype = __proto;
Student.prototype.getAge = function(){
console.log("我是學(xué)生")
}
var stu = new Student("li")
stu.getName();
ES6
class Person{
constructor(name){
this.name = name;
}
getName(){
console.log(this.name)
}
}
class Student extends Person{
constructor(name){
super(name);
}
getName(){
super.getName();
}
}
const stu = new Student("li")
stu.getName();