关于继承的prototype , _proto_, constructor
2016-03-01 22:41
417 查看
1. 最常见的组合式继承
function Parent(p) { this.p = p; } Parent.prototype.get = function() { //注:prototype其中就是一个空对象{},但它是function特有的对象 return this.p; } function Child(c) { Parent.call(this,c); //继承Parent的属性 this.c = 3; } Child.prototype = new Parent(); //现在,child.prototype对象就是Parent的实例,则里面含有 实例属性: p ,目前的值为 undefined,同时此时的 //Child.prototype.constructor = Parent ; var c = new Child(); //在c中又会有一份 实例属性p ; 这是因为: 在new Parent的时候,调用了一次 Parent的构造函数; 当调用Child的构造函数的时候,又调用了一次Parent的构造函数,又会在新对象上创建实例属性 p ; 为了避免这种重复创建属性的过程, 可以选择1 :及时修正 Child.prototype = new Parent(); Child.prototype.constructor = Child; //这可以避免 二次 创建,但是 一次创建的东西是 不会消失啦,也就是Child.prototype中保留着一份 实例属性 选择2 :改变继承方式:寄生组合式继承 function inheritPrototype( w, m) { var p = Object(w.prototype); p.constructor = m; m.prototype = p; } //属性继承不变 function Child(c) { Parent.call(this,c); this.c = c; } inheritPrototype( Parent ,Child ); 点评一下: 其实这个方法是先 偷梁换柱,再交还给 子类 选择3 :野生方法(好像不好看,不过很管用啊,可能效率有点低啦!) function Child( c) { Parent.call(this,c); this.c = c; } for( var i in Parent.prototype ) { Child.prototype[i] = Parent.prototype[i]; } 这样继承的话,Child.pototype.constructor 的值 还是Child 啦!而且Child.prototype中也不会有实例 属性 p; 其实,2、3差不多啦!
相关文章推荐
- 用NFC简化蓝牙配对并互相发送对方的蓝牙的MAC地址
- android自定义电池View
- 关于主配置和虚拟主机配置
- 截图软件
- 算法_9:随机算法
- 10+ 最流行的 jQuery Tree 菜单插件
- 开源一个完整的iOSApp《丁丁美图》供初学者学习
- javascript闭包
- 接口和抽象类有什么区别
- 关于方法区内存溢出!
- 无线智能小车(一)
- 【02】SimpleAdapter和OnScrollListener
- Collocations
- struts(tags)
- 搜索(DLX):HOJ 1017 - Exact cover
- 单例模式
- bzoj 1059: [ZJOI2007]矩阵游戏
- 【计算机视觉】粒子滤波跟踪
- AngularJS 使用 UI Router 实现表单向导
- Eclipse 使用 maven 构建demo