Javascript 原型链与constructor

Javascript中的constructor与prototype

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

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属性。java

咱们来分析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

根据以上代码,咱们分析获得以下链条:
学习

相关文章
相关标签/搜索