原型继承方法记录
来源:互联网 发布:linux php开发工具 编辑:程序博客网 时间:2024/05/16 06:18
// PrimaryStudent构造函数:function PrimaryStudent(props) { Student.call(this, props); this.grade = props.grade || 1;}// 空函数F:function F() {}// 把F的原型指向Student.prototype:F.prototype = Student.prototype;// 把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.prototype:PrimaryStudent.prototype = new F();// 把PrimaryStudent原型的构造函数修复为PrimaryStudent:PrimaryStudent.prototype.constructor = PrimaryStudent;// 继续在PrimaryStudent原型(就是new F()对象)上定义方法:PrimaryStudent.prototype.getGrade = function () { return this.grade;};// 创建xiaoming:var xiaoming = new PrimaryStudent({ name: '小明', grade: 2});xiaoming.name; // '小明'xiaoming.grade; // 2// 验证原型:xiaoming.__proto__ === PrimaryStudent.prototype; // truexiaoming.__proto__.__proto__ === Student.prototype; // true// 验证继承关系:xiaoming instanceof PrimaryStudent; // truexiaoming instanceof Student; // true
借助中间空函数实现 new PrimaryStudent() ----> PrimaryStudent.prototype ----> Object.prototype ----> null
到 new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null
的转变
还可以用封装函数inherits(),可以隐藏F的定义,并简化代码:
function inherits(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child;}
阅读全文
0 0
- 原型继承方法记录
- JS面向对象的继承三种方法:原型继承,原型冒充继承,复制继承
- 完美原型prototype类的继承方法
- JavaScript 原型对象的继承方法
- 关于原型继承的三种方法
- javascript, 原型链,javascript 原型链方法,原型链继承,原型链和作用域链
- 原型继承
- 原型继承
- 原型继承
- 原型继承
- 原型继承
- 原型-原型链-继承
- 8-属性的继承与方法继承图谱(原型链的继承)
- js包装集和扩展方法(原型继承)
- javascript动态原型方法的多继承实现
- js原型链继承及调用父类方法
- 关于js原型和继承的方法复习
- JS:原型、原型链、继承
- Tensorflow---monitoring,saver
- monkeyrunner第一个demo
- JQuery禁用form提交事件
- Markdown编辑器基本格式
- LeetCode Weekly Contest 35解题思路
- 原型继承方法记录
- 过山车
- 5、ThreadLocals实现线程范围内的共享变量
- Ackerman函数的递归、全排列的递归实现、整数划分的递归、二分搜索的递归、合并排序的递归、.快速排序
- 【机房重构】-存储过程
- 23种设计模式及6大原则
- Java 的泛型
- 大数据优秀博客总结
- 各种各样的图