每一个构造函数都有一个属性叫做原型(prototype)。这个属性非常有用:为一个特定类声明通用的变量或者函数。
prototype的定义
你不需要显式地声明一个prototype属性,因为在每一个构造函数中都有它的存在
本文基于下面几个知识点:
1 原型法设计模式
在.net中可以使用clone()来实现原型法
原型法的主要思想是,现在有1个类a,我想要创建一个类b,这个类是以a为原型的,并且能进行扩展。我们称b的原型为a。
2 javascript的方法可以分为三类:
a 类方法
b 对象方法
c 原型方法
例子:
function people(name){ this.name=name; //对象方法 this.introduce=function(){ alert(my name is +this.name); }}//类方法people.run=function(){ alert(i can run);}//原型方法people.prototype.introducechinese=function(){ alert(我的名字是+this.name);} //测试var p1=new people(windking);p1.introduce();people.run();p1.introducechinese();
3 obj1.func.call(obj)方法
意思是将obj看成obj1,调用func方法
好了,下面一个一个问题解决:
prototype是什么含义?
javascript中的每个对象都有prototype属性,javascript中对象的prototype属性的解释是:返回对象类型原型的引用。
a.prototype = new b();
理解prototype不应把它和继承混淆。a的prototype为b的一个实例,可以理解a将b中的方法和属性全部克隆了一遍。a能使用b的方法和属性。这里强调的是克隆而不是继承。可以出现这种情况:a的prototype是b的实例,同时b的prototype也是a的实例。
先看一个实验的例子:
function baseclass(){ this.showmsg = function() { alert(baseclass::showmsg); }}function extendclass(){}extendclass.prototype = new baseclass();var instance = new extendclass();instance.showmsg(); // 显示baseclass::showmsg
我们首先定义了baseclass类,然后我们要定义extentclass,但是我们打算以baseclass的一个实例为原型,来克隆的extendclass也同时包含showmsg这个对象方法。
extendclass.prototype = new baseclass()就可以阅读为:extendclass是以baseclass的一个实例为原型克隆创建的。
那么就会有一个问题,如果extendclass中本身包含有一个与baseclass的方法同名的方法会怎么样?
下面是扩展实验2:
function baseclass(){ this.showmsg = function() { alert(baseclass::showmsg); }}function extendclass(){ this.showmsg =function () { alert(extendclass::showmsg); }}extendclass.prototype = new baseclass();var instance = new extendclass();instance.showmsg();//显示extendclass::showmsg
实验证明:函数运行时会先去本体的函数中去找,如果找到则运行,找不到则去prototype中寻找函数。或者可以理解为prototype不会克隆同名函数。
那么又会有一个新的问题:
如果我想使用extendclass的一个实例instance调用baseclass的对象方法showmsg怎么办?
答案是可以使用call:
extendclass.prototype = new baseclass();var instance = new extendclass();var baseinstance = new baseclass();baseinstance.showmsg.call(instance);//显示baseclass::showmsg
这里的baseinstance.showmsg.call(instance);阅读为“将instance当做baseinstance来调用,调用它的对象方法showmsg”
好了,这里可能有人会问,为什么不用baseclass.showmsg.call(instance);
这就是对象方法和类方法的区别,我们想调用的是baseclass的对象方法
最后,下面这个代码如果理解清晰,那么这篇文章说的就已经理解了:
以上内容是关于js中prototype的理解,希望大家喜欢。