javascript继承
来源:互联网 发布:打车软件有几种 编辑:程序博客网 时间:2024/06/05 13:05
//原型继承
/*定义一个人类*/ function Person(name){ this.property = 1; } //声明父类方法 Person.prototype.getPersonValue = function(){ return this.property; } //声明子类构造函数 function Student(){ this.subproperty = 2; } //声明子类方法 Student.prototype.getStudentValue = function(){ return this.subproperty; } Student.prototype = new Person("chentao"); Student.prototype.constructor = Student; var studentIns = new Student(); console.log(studentIns.getPersonValue());
原型继承是有缺陷的,主要有两个问题; 一. 包含引用类型值的原型,会被所有实例共享。
function Person(){} Person.prototype = { constructor : Person, friends : ["greg","jack"] } var person1 = new Person(); var person2 = new Person(); person1.friends.push("tom"); console.log(person2.friends);
可以看到person2的实例中多了一个'tom',这并不是我们想要的. 二. 创建子类型的实例时,不能向超类型的构造函数中传递参数。 原型链的继承,直接将子类原型指向超类的实例,这时候可以向超类传递参数。 但是当子类创建实例的时候,只能向子类的构造函数传递参数,而不能向超类的构造函数传递参数。
//构造函数继承
function Person(){ this.colors = ["red","blue","green"]; } function Student(){ Person.call(this); } var student1 = new Person(); student1.colors.push("black"); console.log(student1.colors); var student2 =new Person(); console.log(student2.colors);
通过构造函数继承,改变了原型继承的缺陷. 可以看到这里继承了父类的引用类型值,但是子类的不同实例间没有相互影响 同时,这样还可以在继承中向父类传递参数.
//典型的javascript继承:
/*定义一个人类*/ function Person(name,age) { this.name=name; this.age=age; this.property = true; } Person.prototype.getPersonValue = function(){ return this.property; } /*定义一个学生类*/ function Student(name,age,grade) { Student.call(this,name,age); this.grade=grade; this.subproperty = false; } Student.prototype = Object.create(Student.prototype);; Student.prototype.constructor = Student; Student.prototype.getStudentValue = function(){ return this.subproperty; }; //创建一个学生类 var student = new Student("chentao",24,"一年级"); //测试 console.log(student.getPersonValue()); alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);
0 0
- javascript继承
- javascript继承
- javascript 继承
- Javascript继承
- Javascript继承
- javascript继承
- Javascript继承
- javascript继承
- JavaScript 继承
- javascript 继承
- JavaScript 继承
- javascript 继承
- javascript 继承
- Javascript继承
- Javascript继承
- Javascript 继承
- JavaScript 继承
- javascript继承
- Java学习笔记2:Java中Integer与String == 的使用
- IOS开发缓存机制之—内存缓存机制
- JAVA面试题大全整理
- android studio 使用NDK
- KM(n^4)模板
- javascript继承
- C++重载
- 设置navigationbar透明
- HDU 3991 Harry Potter and the Present II(Floyd+DAG最小路径覆盖)
- android面试题目2
- C语言进阶
- 图的遍历
- http://blog.csdn.net/innost?viewmode=contents
- ios打印NSInteger的时候去除警告