在学习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对象的建立过程:
编程
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
根据以上代码,咱们分析获得以下链条:
学习