JavaScript学习笔记3-JavaScript中的继承2
2015-09-02 13:58
736 查看
3) apply方法方式
4)原型链方式(无法给构造函数传参数)
5)混合方式(推荐)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title> New Document </title> <meta name="Generator" content="EditPlus"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <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.sayWorld = function() { alert(this.password); } } var parent = new Parent("zhangsan"); var child = new Child("lisi", "123"); parent.sayHello(); child.sayHello(); child.sayWorld(); </script> </head> <body> </body> </html>
4)原型链方式(无法给构造函数传参数)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title> New Document </title> <meta name="Generator" content="EditPlus"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <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.world = "world"; Child.prototype.sayWorld = function() { alert(this.world); } var child = new Child(); child.sayHello(); child.sayWorld(); </script> </head> <body> </body> </html>
5)混合方式(推荐)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title> New Document </title> <meta name="Generator" content="EditPlus"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <script type="text/javascript"> //使用混合方式实现对象继承(推荐) function Parent(hello) { this.hello = hello; } Parent.prototype.sayHello = function() { alert(this.hello); } function Child(hello, world) { Parent.call(this, hello); //这句不会把sayHello方法设置到Child对象中,因此需要重新 <span style="font-family: Arial, Helvetica, sans-serif;">Child.prototype = new Parent();</span> this.world = world; } Child.prototype = new Parent(); Child.prototype.sayWorld = function() { alert(this.world); } var child = new Child("hello", "world"); child.sayHello(); child.sayWorld(); </script> </head> <body> </body> </html>
相关文章推荐
- js模板引擎介绍搜集
- Java与JavaScript
- 3D动态词云—JavaScript
- JSP实战项目教程|基于JSP的学生请假系统开发视频教程
- JS实现弹性漂浮效果的广告代码
- js的选择星级评分插件
- JS 中刷新页面的方法
- js判断鼠标滚动方向
- JS --正则表达式
- js随机生成字母数字组合的字符串 随机动画数字
- JS函数调用
- js鼠标键禁用功能
- JS自定义选项卡函数及用法实例分析
- 有关onsubmit return false 阻止form表单提交:js
- js图片滑动切换效果
- javascript中for/in循环及使用技巧
- js鼠标点击按钮切换图片-图片自动切换-点击左右按钮切换特效代码
- AJAX+js实现实时聊天
- js定时器
- js 限制输入的字数及其剩余字数的提示