Javascript 原型链与constructor

本文解析了JavaScript中构造函数的constructor属性与prototype属性的关系,通过实例详细解释了如何利用原型链实现继承。

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

根据以上代码,我们分析得到如下链条:
976193-20170601100018164-2112851820.png

转载于:https://www.cnblogs.com/Nancy-wang/p/6907995.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值