• Javascript 原型链与constructor


    Javascript中的constructor与prototype

    在学习javascript面向对象编程的过程中, constructor和prototype一直让我觉得理解不透,慢慢的学习过程中记录自己的理解,加深印象,故写下此篇。
    首先来看一个例子:

            function Person(name) {
                this.name = name;
                this.showName = function() {
                    console.log(this.name);
                }
            }
            var student = new Person("COCO");
            student.showName();//COCO
            console.log(student.prototype);//undefined
            console.log(Person.prototype);//Object {constructor: function}
            console.log(Person.prototype.constructor);//function Person(name){...}
    

    在之前的文章中有提到:使用function定义的对象与使用new操作符生成的对象之间有一个重要的区别,就是function定义的对象有一个prototype属性,使用new生成的对象就没有这个prototype属性,因此student对象并没有prototype属性。

    我们来分析student对象的创建过程:

    1. 建立一个新的对象student
    2. 对象创建时存在预定义的属性,我们称之为内置原型对象,即__proto__,用新建student的内置原型对象指向构造函数的原型对象,即student.__proto__==Person.prototype
    3. 将新建对象student作为this参数调用构造函数(Person),即Person.call(student); 也就是说构造student,也可以称之为初始化student
    通过student的内置原型对象,可以访问到Person的prototype对象中的任何属性与方法了,因为prototype对象中存在一个constructor属性,那么student也可以直接访问constructor属性。因此我们可以理解如下代码:
    console.log(student.constructor == Person.constructor)//false
    console.log(student.constructor == Person.prototype.constructor)//true
    console.log(Person.constructor==Function.prototype.constructor)//true
    //Person对象的构造函数是Function,因此Person对象的constructor指向Function.prototype的constructor
    
    

    根据以上的结论,我们来分析如何通过原型链实现继承:

            function Father(name) {
                this.name = name;
                this.showName = function() {
                    console.log(name);
                }
            }
    
            Father.prototype.home = function() {
                console.log("Shanghai");
            }
    
            function son() {}
    
            son.prototype = new Father();//继承实现的关键,将子类的prototype设置为父类的一个对象
            console.log(son.prototype.constructor); //function Father(name) {}
    
            var firstSon = new son();
    
            firstSon.home(); //Shanghai
            console.log(firstSon.constructor); //function Father(name) {}
            console.log(son.prototype.constructor); //function Father(name) {}
            console.log(firstSon.constructor == son.prototype.constructor); //true
    

    根据以上代码,我们分析得到如下链条:

  • 相关阅读:
    MongoDB安装&启动
    MongoDB集群搭建
    树与二叉树
    git入门
    MongoDB Java Driver
    Spring整合Junit4
    SQL字符串的数字部分递增
    [求职经历反面教材]4周面试20家,面霸磨成面瘫,仅供初级程序员参考!
    简陋的信息采集方式
    由一个博问学到的SQL查询方法 (一道多对多关系查询的面试题)
  • 原文地址:https://www.cnblogs.com/Nancy-wang/p/6907995.html
Copyright © 2020-2023  润新知