baiseda 发表于 2013-1-29 09:14:52

javascript学习笔记 (五) -继承和Closures



<div class="postBody">javascript中的继承和Closures
实现继承的两种方法
使用"call"函数,call允许我们在一个上下文环境中调用另外一个函数。我们在cat和dog类中调用animal类。
<div style="border: 1px solid #cccccc; padding: 4px 5px 4px 4px; background-color: #eeeeee; width: 98%; font-size: 13px;"><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->functionAnimal(name){
this.name=name;

this.species='Animal';
this.sleep=function(){alert(this.name+'fallsasleep:Zzzzz');}
}
functionCat(name){
Animal.call(this,name);

this.talk=function(){alert('Meow!');}
}
functionDog(name){
Animal.call(this,name);

this.talk=function(){alert('Woof!');}
}

varsam=newCat('Sam');
varjoe=newDog('Joe');
sam.sleep();//Samfallsasleep:Zzzzz
joe.sleep();//Joefallsasleep:Zzzzz

sam.talk();//Meow!
joe.talk();//Woof!
页: [1]
查看完整版本: javascript学习笔记 (五) -继承和Closures