zoukankan      html  css  js  c++  java
  • 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
    

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

  • 相关阅读:
    推荐一个博客,或许给技术流的自己一些启示
    Boost多线程-替换MFC线程
    Python:Matplotlib 画曲线和柱状图(Code)
    AI:机器人与关键技术--总是被科普
    OnLineML一:关于Jubatus 的简介...
    使用PCL::GPU::遇到问题
    dll文件:关于MFC程序不能定位输入点
    实践:使用FLANN.LSH进行检索
    模式识别两种方法:知识和数据
    几个方便编程的C++特性
  • 原文地址:https://www.cnblogs.com/Nancy-wang/p/6907995.html
Copyright © 2011-2022 走看看