原型对象和原型链

2018-06-09  本文已影响0人  小小小前端

概念

1.原型对象(prototype) 只有函数有原型对象 相当于每个函数具有一个prototype属性,所指向的对象,就叫原型对象
2.原型链由对象的proto 继承连接下来,对象的proto指向其构造函数的原型对象,其中对象包括普通对象和函数对象

实例详解

    function Car() {
        
    }
    var car = new Car();

    console.log(car.__proto__ === Car.prototype);//car 是非函数对象 只有__proto__属性
    console.log(car.__proto__.__proto__  === Object.prototype)//car.__proto__.__proto__ = Car.prototype.__proto__ = Object.prototype
    console.log(car.__proto__.prototype)  //undefined
    //总结的普通对象的__proto__最终都指向Object.prototype,普通对象没有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__)

    //所有函数对象都有原型对象   所有函数对象的(一级)__proto__指向Function.prototype(空函数) 最终指向Object.prototype

    console.log(Function.prototype === Function.__proto__);//true
    console.log(Function.prototype === Object.__proto__)//true

总结

所有普通对象的的最终proto 都指向Object.prototype
所有函数对象的一级proto 都指向Function.prototype(空函数) 最终proto还是指向Object.prototype
所有函数对象都有prototype,他们的原型对象proto最终都指向Object.proto,没有prototype对象,原型对象都有constructor属性 指向构造函数本身。函数对象包括 Function Object,Array,Date等函数。

继承

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("我是学生")
    }
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();
上一篇 下一篇

猜你喜欢

热点阅读