再谈原型链,深刻理解原型及原型链(案例分析,详细图解,一目了然)
来源:互联网 发布:redis 高并发读写优化 编辑:程序博客网 时间:2024/06/05 17:10
一、前言:这个案例稍微有些难度,需要掌握基本的原型、原型链、构造函数、继承等相关知识,如若还没有掌握,不妨看看我的这篇博客,详细介绍了这些知识及关系:http://blog.csdn.net/spicyboiledfish/article/details/71123162
二、首先看看这个案例,源代码附上:
function Person(name,age){ this.name=name; this.age=age;}Person.prototype.hi=function(){ console.log("Hi,my name is"+this.name+",I'm"+this.age+"years old now.");};Person.prototype.LEGS_NUM=2;Person.prototype.ARMS_NUM=2;Person.prototype.walk= function () { console.log(this.name+"is walking...");};function Student(name,age,className){ Person.call(this,name,age); this.className=className;}Student.prototype=Object.create(Person.prototype);Student.prototype.constructor=Student;Student.prototype.hi=function(){ console.log("Hi,my name is "+this.name+" ,I'm "+ this.age+" years old now,and from "+this.className+".");};Student.prototype.learn=function(subject){ console.log(this.name+"is learning "+subject+" at "+this.className+".");};//testvar bosn=new Student("Bosn",27,"Class 3,Grade 2");bosn.hi(); //Hi,my name is Bosn,I'm 27 years old now,and from Class 3,Grade 2.bosn.LEGS_NUM; //2bosn.walk(); //Bosnis walking...bosn.learn("math"); //Bosnis learning math at Class 3,Grade 2.
三、由以上代码,可以轻松在控制台打印出相应的结果。
有个难点:Student.prototype=Object.create(Person.prototype);是将Student.prototype的原型继承指向Person.prototype;为什么不使用Student.prototype=Person.prototype呢?因为Student.prototype会有自己独有的方法,譬如learn(){},如果改成这句代码,那么添加或修改Student.prototype的属性方法后,Person.prototype的属性和方法也会跟着被修改了,因为这两者已经指向了同一个对象。
如下:即为以上代码所体现出的完整的原型链结构图,尽情观赏:
四、如果修改Student.prototype属性方法,结果又如何呢?上源码并附上详细图解:
Student.prototype.x=101;console.log(bosn.x); //101Student.prototype={y:2};console.log(bosn.y); //undefinedconsole.log(bosn.x); //101var nunnly=new Student("Nunnly",3,"Class LOL KengB");console.log(nunnly.x); //undefinedconsole.log(nunnly.y); //2
解释:
1.Student.prototype.x=101;意思为Student.prototype添加一个属性x为101,所以访问bosn.x=101;
2.Student.prototype={y:2};意思是替换对象属性,系统会重新开辟一块空间放一个对象{y:2},且指针的指向也变化了,Student.prototype就指向了新的对象{y:2};
3.访问bosn.y;首先在bosn对象本身寻找,没有,去bosn的原型找,发现也没有,这时候只能返回undefined;访问bosn.x仍然返回时101;
4.重新创建一个对象nunnly,那么这个实例划对象的原型是指向新的原型对象的{y:2};
5.访问nunnly.x未找到,返回undefined;访问nunnly.y返回2;
五、Github源码:https://github.com/spicyboiledfish/JavaScript-testJS
- 再谈原型链,深刻理解原型及原型链(案例分析,详细图解,一目了然)
- JavaScript的原型原型链的深刻理解及运用
- 图解原型原型链
- 理解原型及原型链(笔记)
- 原型链详细分析
- 简单理解javascript原型及原型链
- 理解原型和原型链
- JS原型及原型链
- 图解Javascript原型链
- 图解Javascript原型链
- 图解Javascript原型链
- JS原型链图解
- 原型链图解
- 图解原型链
- Javascript原型和原型链图解
- 图解js原型对象、原型链
- 完整原型链详细图解(构造函数、原型、实例化对象)
- 完整原型链详细图解(构造函数、原型、实例化对象)
- JVM(一) 一个小程序吸引了我
- 在网站开发中加入折线图
- javascript编码规范
- C#分部类型解析
- HDU 5336 XYZ and Drops
- 再谈原型链,深刻理解原型及原型链(案例分析,详细图解,一目了然)
- Java基础——"=="和equals方法究竟有什么区别?
- MySQL学习笔记创建表
- SSM 框架 搭建
- [Leetcode] 135. Candy 解题报告
- nio demo
- Android Studio项目与Git托管
- 血坑!!!!cronolog拆分tomcat catelina.log日志吐血总结
- HTML5开发笔记:初窥CANVAS,上传canvas图片到服务器