Js中的prototype

来源:互联网 发布:sql笔试题及答案 编辑:程序博客网 时间:2024/06/04 13:48


   最近新入职了一家公司,周五看代码的时候,发现他们页面上的js是这样纸的,我当时的心情是莫名其妙的:




好吧,入乡随俗。


prototype通俗的用法,就是向对象添加属性跟方法。


/*  javascript中的每个对象都有prototype属性,js中对象的prototype属性的解释是,返回对象类型原型的引用。  A.prototype=new B();  理解prototype不应把它和继承混淆。  这里强调的是克隆而不是继承。 */function People(name){  this.name=name;  //对象方法  this.Introduce=function(){    alert("my name is "+this.name);  }}//类方法People.Run=function(){  alert("i am running...");}//原型方法People.prototype.IntroduceChinese=function(){  alert("我的名字是:"+this.name);}//测试var p1=new People("lhc");p1.Introduce();People.Run();p1.IntroduceChinese();

通过prototype,起到了一个克隆方法的作用。


下面来瞅瞅使用原型的时候,可能会遇到的问题。


问题一:扩展类与对象实例具有相同的方法,调用时候会调用哪一个?



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不会克隆同名函数。






0 0
原创粉丝点击