理顺 JavaScript (15) - 类的继承手段: prototype
2021/4/29 22:25:28
本文主要是介绍理顺 JavaScript (15) - 类的继承手段: prototype,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
理顺 JavaScript (15) - 类的继承手段: prototype
prototype(原型) 是 JavaScript 中类的继承手段;
一个类也不过是一组属性和方法的集合, 所谓继承就是继承属性或方法;
属性是个值, 方法是个函数, JavaScript 喜欢把它们都叫成属性, 我们喜欢把它们叫做成员;
JavaScript 默认让每个函数都拥有一个 prototype 对象, 它可以指向一个对象或函数(函数也是对象, 一回事);
绕来绕去, 最终是四通八达...
类成员与对象成员
function Rect(w, h) { Rect.name = "My Rect"; //静态成员属于类, 不会被对象继承; 须冠类名调用 this.width = w; //this 是指实例化以后的对象或调用该函数的对象 this.height = h; xyz = 123; //这只能当个内部变量来使用 } var r = new Rect(); //判断指定的成员名是否属于对象 alert("width" in r); //true alert("height" in r); //true alert("name" in r); //false //遍历对象成员 for (x in r) { alert(x); //width / height } //遍历类成员 for (x in Rect) { alert(x); //name }
继承
function Point(x, y) { this.x = x; this.y = y; }; function Rect(w, h) { Rect.name = "My Rect"; this.width = w; this.height = h; } Rect.prototype = new Point(); //让 Rect 再从 Point 类继承 var r = new Rect(); //继承以后就可以这样使用 r.x = 1; r.y = 2; r.width = 3; r.heigth = 4; //遍历对象成员 for (x in r) { alert(x); //y / x / width / height } //遍历类成员 for (x in Rect) { alert(x); //name } //建立方法 constructor 属于 prototype, 既然 Rect 是继承与 Point, 那么: alert(r.constructor); /* 将显示: function Point(x, y) { this.x = x; this.y = y; }; */
hasOwnProperty、propertyIsEnumerable、isPrototypeOf
function Point(x, y) { this.x = x; this.y = y; }; function Rect(w, h) { Rect.name = "My Rect"; this.width = w; this.height = h; } Rect.prototype = new Point(); var r = new Rect(); /* 可用 hasOwnProperty 方法判断指定成员是否是对象的固有成员(而非继承来的) */ alert(r.hasOwnProperty('x')); //false alert(r.hasOwnProperty('y')); //false alert(r.hasOwnProperty('width')); //true alert(r.hasOwnProperty('height')); //true /* 但不能用 hasOwnProperty 判断成员是否是继承来的, 譬如 */ alert(r.hasOwnProperty('ABCDEFG')); //false /* propertyIsEnumerable */ alert(r.propertyIsEnumerable('x')); //false alert(r.propertyIsEnumerable('y')); //false alert(r.propertyIsEnumerable('width')); //true alert(r.propertyIsEnumerable('height')); //true /* isPrototypeOf: 是不是参数(参数是个对象)的原型对象 */ alert(Point.prototype.isPrototypeOf(r)); //true alert(Rect.prototype.isPrototypeOf(r)); //true alert(r.isPrototypeOf(r)); //true var obj = {}; alert(Object.prototype.isPrototypeOf(obj)); //true var str = new String(); alert(String.prototype.isPrototypeOf(str)); //true alert(Object.prototype.isPrototypeOf(str)); //true
这篇关于理顺 JavaScript (15) - 类的继承手段: prototype的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现