日期:2014-05-16 浏览次数:20494 次
<script type="text/javascript"> //使用call实现继承 function parent(username){ this.username=username; this.sayHello=function(){ alert(this.username); } } function child(username,password){ parent.call(this,username); this.password=password; this.sayWord=function(){ alert(this.password); } } var p=new parent("hello"); var c=new child("word","123"); p.sayHello(); c.sayHello(); c.sayWord(); </script>
?apply方法方式:
<script type="text/javascript"> //apply方法实现对象继承 function parent(username){ this.username=username; this.sayHello=function(){ alert(this.username); } } function child(username,password){ parent.apply(this,new Array(username)); this.password=password; this.sayWord=function(){ alert(this.password); } } var p=new parent("hello"); var c=new child("word","123"); p.sayHello(); c.sayHello(); c.sayWord(); </script>
?原型链方式:无法给构造函数传递参数
<script type="text/javascript"> //使用原型链(prototype chain)实现对象的继承 function parent(){} parent.prototype.hello="hello"; parent.prototype.sayHello=function(){ alert(this.hello); } function child(){} child.prototype=new parent(); child.prototype.word="word"; child.prototype.sayWord=function(){ alert(this.word); } var p=new parent(); var c=new child(); p.sayHello(); c.sayHello(); c.sayWord(); </script>
?混合方式:(推荐使用)
<script type="text/javascript"> //使用混合方式实现对象的继承 function parent(hello){ this.hello=hello; } parent.prototype.sayHello=function(){ alert(this.hello); } function child(hello,word){ //实现属性的继承 parent.call(this,hello); this.word=word; } //实现方法的继承 child.prototype=new parent(); child.prototype.sayWord=function(){ alert(this.word); } var p=new parent("hello"); var c=new child("word","123"); p.sayHello(); c.sayHello(); c.sayWord(); </script>
?学到这里,javascript的核心应该已经学完了,可是自己感觉没什么进步,不知道大家是怎么在学习啊,希望大家能指教指教小弟。
?