JavaScript原型链继承的对比
来源:互联网 发布:淘宝网 欧瑞斯的价格 编辑:程序博客网 时间:2024/06/05 04:44
1、代码
function Person(name, age) {this.name = name;this.age = age;}Person.prototype.sayHello = function() {console.log("My name is " + this.name + ", and age is " + this.age);}function Student() {}
2、通过Student.prototype = Person.prototype 的继承方式
2.1 继承的实现
1. 代码
Student.prototype = Person.prototype;var studentA = new Student();
2. 结果查看
2.2 缺点:在子类的原型里面,添加的方法和属性,父类对象也可以访问到
3、通过 Student.prototype = new Person() 的继承方式
3.1 继承的实现
1. 代码
Student.prototype = new Person();var studentA = new Student();
2. 结果的查看
3.2 缺点:在子类的 对象里面,会拥有父类中非原型的属性(例如age,name属性)
4、通过C.prototype = Object.create(Person.prototype)的继承方式
4.1.继承的实现
1. 代码
Student.prototype = Object.create(Person.prototype);var studentA = new Student();2. 结果的查看
4.2.缺点(完美)
4.3 Object.create()的内部实现
function create(clazz) {function F() {};F.prototype = clazz;var _protoType = new F();return _protoType;}
5、constructor修正问题(Student.prototype.constructor = Student;)
Student.prototype = Object.create(Person.prototype);Student.prototype.constructor = Student;
6、完整的参考代码
<script>function create(clazz) {function F() {};F.prototype = clazz;var _protoType = new F();return _protoType;}function Person(name, age) {this.name = name;this.age = age;}Person.prototype.sayHello = function() {console.log("My name is " + this.name + ", and age is " + this.age);}function Student() {}//通过原型链的方式,完成方法的继承//Student.prototype = Person.prototype;//Student.prototype = new Person();Student.prototype = Object.create(Person.prototype);var studentA = new Student();</script>
1 0
- JavaScript原型链继承的对比
- JavaScript的继承--原型链
- JavaScript的原型继承
- JavaScript的原型继承
- javascript原型链继承
- javascript原型链继承
- JavaScript:原型链、继承
- javascript 原型链继承
- JavaScript 继承---原型链
- JavaScript中原型链继承的问题
- JavaScript的只继承于原型链
- JavaScript的封装,继承 | 原型链
- javascript中的原型(prototype)及原型链的继承方式
- javascript中的原型(prototype)及原型链的继承方式
- javascript中继承(一)-----原型链继承的个人理解
- javascript 的 继承(一) 之 原型链继承
- javascript中继承(一)-----原型链继承的个人理解
- javascript基于原型的继承
- [Warning] TIMESTAMP with implicit DEFAULT value is deprecated.
- 框架和类库的区别
- imessage使用二
- 没那么难,谈CSS的设计模式
- HDU 6005 Pandaland(dijkstra + 剪枝)
- JavaScript原型链继承的对比
- 图像信号的统计特性
- SEO Ultimate 7.6.5.9汉化版(中文版)免费下载
- Spring、SpringMVC、MyBatis、freeMaker框架下之Excel文件导出
- PL/SQL查询中文乱码问题
- 系列笔记11、观察者模式-ListView与Adapter
- SWT简介
- js实现简易的计算器
- YOLO中参数和函数说明