原型是 Js 中非常重要的概念,每个函数 ( 在 Js 里面函数也是对象 ) 都有一个叫 prototype 即原型 ) 的属性,不过在一般情况下它的值都是 null ,但它他有一项非常重要的功能就是所有实例都会共享它里面的属性和方法 ( 这就是 Js 里面实现继承的基础 ) 。
在 JavaScript 中, prototype 对象是实现面向对象的一个重要机制。每个函数就是一个对象( Function ),函数对象都有一个子对象 prototype 对象,类是以函数的形式来定义的。 prototype 表示该函数的原型,也表示一个类的成员的集合。在通过 new 创建一个类的实例对象的时候, prototype 对象的成员都成为实例化对象的成员。
function 定义的对象有一个 prototype 属性,使用 new 生成的对象就 没有 这个 prototype 属性 。
prototype 属性 又指向了一个 prototype 对象 ,注意 prototype 属性 与 prototype 对象 是两个不同的东西,要注意区别。在 prototype 对象中又有一个 constructor 属性,这个 constructor 属性 同样指向一个 constructor 对象 ,而这个 constructor 对象恰恰就是这个 function 函数本身,见下图示例:
验证代码:
function Person(name) { this.name=name; this.showMe=function() { alert(this.name); } }; var one=new Person('js'); alert(one.prototype)//undefined alert(typeof Person.prototype);//object alert(Person.prototype.constructor);//function Person(name) {...};
实例是通过构造函数创建,但是跟构造函数没有直接关系,其内部的 __proto__ 属性 指向了 prototype ,而 prototype (原型)的 constructor 指向了构造函数,构造函数的 prototype 属性指向了原型( prototype ),所以说实例跟构造函数都是通过 prototype 发生了关系....
继承的实现很简单,只需要把子类的 prototype 设置为父类的一个(实例化)对象 即可。注意这里说的可是对象哦!
那么通过 prototype 属性实现继承的原理是什么呢?还是先看图形说明,然后编写代码进行验证。
注意:红色的方框就是把子类与父类链接起来的地方。这个就应该是传说中的 prototype 链了吧。下面有代码进行验证。
function Person(name){ this.name=name; this.showMe=function(){ alert(this.name); } }; Person.prototype.from=function(){ alert('I come from prototype.'); } var father=new Person('js');//为了下面演示使用showMe方法,采用了js参数,实际多采用无参数 alert(father.constructor);//查看构造函数,结果是:function Person(name) {...}; function SubPer(){ } SubPer.prototype=father;//注意这里 SubPer.prototype.constructor=SubPer; var son=new SubPer(); son.showMe();//js son.from();//I come from prototype. alert(father.constructor);//function SubPer(){...} alert(son.constructor);//function SubPer(){...} alert(SubPer.prototype.constructor);//function SubPer(){...}