您的位置:首页 > Web前端 > JavaScript

javascript学习随笔(二)原型prototype

2015-05-19 14:18 423 查看
JavaScript三类方法:

1、类方法;2、对象方法;3、原型方法;注意三者异同

例:

function People(name){
this.name=name;
//对象方法
this.Introduce=function(){
console.log('My Name Is '+this.name);
}
}

//类方法
People.Run=function(){
console.log('I Can Run');
}

//原型方法
People.prototype.IntroduceChinese=function(){
console.log('我的名字是'+this.name);
}

//测试
var p=new People('Tom');

p.Introduce();
People.Run();
p.IntroduceChinese();


JavaScript对象类型原型引用,切记将某对象的原型赋给某对象原型,这不是继承关系,而是将克隆,且存在冲突函数或属性时,保留自己的函数和属性

例1、

function  BaseClass(){
this.showMsg=function(){
alert('baseClass::showMsg');
};
}

function  ExtendClass(){

}

ExtendClass.prototype=new BaseClass();

var extend=new ExtendClass();
extend.showMsg();//弹出baseClass::showMsg


例2、

function  BaseClass(){
this.showMsg=function(){
alert('bassClass::showMsg');
};
}

function  ExtendClass(){
this.showMsg=function(){
alert('extendClass::showMsg');
};
}

ExtendClass.prototype=new BassClass();

var extend=new ExtendClass();
extend.showMsg();//弹出extendClass::showMsg


函数运行时会先去本体的函数中去找,如果找到则运行,找不到则去prototype中寻找函数。或者可以理解为prototype不会克隆同名函数.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: