js原生设计模式——2面向对象编程之继承—new类式继承
2015-11-04 17:08
561 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>classInherit</title>
<script type="text/javascript">
//声明父类
function superClass(){
this.name = 'Lucy';
}
superClass.prototype.getName = function(){
console.log(this.name);
}
//声明子类
function subClass(){
this.subname = 'Lilei';
this.books = ['html','css','js'];
}
//类式继承
subClass.prototype = new superClass();
//注:一定要先继承,再添加子类原型方法,否则子类的实例调用子类原型方法时会报错:function is not defined
subClass.prototype.getSubName = function(){
console.log(this.subname);
}
//将子类的prototype原型constructor属性的指向修正为subClass子类,否则继承后默认指向了父类的原型上,会出问题
subClass.prototype.constructor = subClass;
//实例化对象测试
var test1 = new subClass();
var test2 = new subClass();
console.log(test1.name); //Lucy
console.log(test1.subname); //Lilei
test1.getName(); //Lucy
test1.getSubName(); //Lilei
// console.log(test1.books);
test1.books.push('php');
console.log(test1.books); //输出:["html", "css", "js", "php"]
console.log(test2.books); //输出:["html", "css", "js"]
// 两个实例之间不会影响
//本例已经通过验证
</script>
</head>
<body>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>classInherit</title>
<script type="text/javascript">
//声明父类
function superClass(){
this.name = 'Lucy';
}
superClass.prototype.getName = function(){
console.log(this.name);
}
//声明子类
function subClass(){
this.subname = 'Lilei';
this.books = ['html','css','js'];
}
//类式继承
subClass.prototype = new superClass();
//注:一定要先继承,再添加子类原型方法,否则子类的实例调用子类原型方法时会报错:function is not defined
subClass.prototype.getSubName = function(){
console.log(this.subname);
}
//将子类的prototype原型constructor属性的指向修正为subClass子类,否则继承后默认指向了父类的原型上,会出问题
subClass.prototype.constructor = subClass;
//实例化对象测试
var test1 = new subClass();
var test2 = new subClass();
console.log(test1.name); //Lucy
console.log(test1.subname); //Lilei
test1.getName(); //Lucy
test1.getSubName(); //Lilei
// console.log(test1.books);
test1.books.push('php');
console.log(test1.books); //输出:["html", "css", "js", "php"]
console.log(test2.books); //输出:["html", "css", "js"]
// 两个实例之间不会影响
//本例已经通过验证
</script>
</head>
<body>
</body>
</html>
相关文章推荐
- js原生设计模式——2面向对象编程之js原生的链式调用
- js原生设计模式——2面向对象编程之闭包2
- js原生设计模式——2面向对象编程之闭包1
- JSON语法规则
- JS编写选择年份控件
- JS学习--用JS读取本地文件
- 【javascript高级程序设计笔记】第六章OOP
- JSP如何保存页面上众多的复选状态
- 关于url传值出现乱码的问题记录
- [js开源组件开发]localStorage-cache本地存储的缓存管理
- JS中document.createElement()的用法
- js实现可拉伸移动的div
- javascript设计模式-学习笔记
- Javascript模块化编程(三):require.js的用法
- js获取本月第几周和本年第几周
- javascript中 visibility和display的区别
- PhantomJS快速入门
- js打开指定页面
- js书籍笔记《一》
- dataset或dataTable转成json串