概述
最近新入职了一家公司,周五看代码的时候,发现他们页面上的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不会克隆同名函数。
最后
以上就是隐形纸飞机为你收集整理的Js中的prototype的全部内容,希望文章能够帮你解决Js中的prototype所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复