关于js原型继承的理解
2017-03-23 19:54
543 查看
//原型继承 function SuperType(){ this.property = true ; } console.log("SuperType()=",SuperType()); SuperType.prototype.getSuperValue = function(){ return this.property; } console.log("SuperType.prototype()=",SuperType.prototype()); function SubType(){ this.subproperty = false; } console.log("SubType()=",SubType()); //继承了SuperType SubType.prototype = new SuperType(); console.log("SubType.prototype()=",SubType.prototype()); SubType.prototype.getSubValue = function(){ return this.subproperty; } console.log("SubType.prototype()=",SubType.prototype()); var instance = new SubType(); alert(instance.getSuperValue()); //call继承 function A(){ this.x = 100; console.log("A--->this=",this); } A.prototype.getX = function(){ console.log("A.prototype.getX--->this.x=",this.x); } function B(){ console.log("B--->this=",this); A.call(this); } console.log("B.prototype=",B.prototype); var n = new B; console.log(n.x); //冒充对象继承 /** * 冒充对象继承会把父类 私有的+公有的 都克隆一份一模一样的给子类私有的 */ function A(){ this.x = 100; } A.prototype.getX = function(){ console.log(this.x); } function B() { var temp = new A; for(var key in temp){ this[key] = temp[key]; } temp = null; } console.log("B=",B); console.log("B.prototype=",B.prototype); var n = new B; console.log("n._proto_=",n._proto_); console.log(n.x); //混合式继承 /** * 混合式继承就是原型继承+call继承 * @constructor */ function A(){ this.x = 100; } A.prototype.getX = function(){ console.log(this.x); } function B(){ A.call(this); } B.prototype = new A; console.log("B.prototype=",B.prototype); // B.prototype.constructor = B; console.log("B.prototype=",B.prototype); var n = new B; n.getX(); //寄生组合式继承 /** * */ function A(){ this.x = 100; } A.prototype.getX = function(){ console.log(this.x); } function B(){ A.call(this); } B.prototype = Object.create(A.prototype); //IE6,7,8不兼容 B.prototype = objectCreate(A.prototype); B.prototype.constructor = B; console.log("B.prototype=",B.prototype); var n = new B; console.dir(n); function objectCreate(o){ function fn(){} fn.prototype = o; return new fn; } /** * gao 3 */ function SuperType(name) { this.name = name; this.colors = ["red","blue","green"]; } SuperType.prototype.sayName = function(){ alert(this.name); } function SubType(name,age){ SuperType.call(this,name); this.age = age; } inheritPrototype(SubType,SuperType); SubType.prototype.sayAge = function(){ alert(this.age); } function inheritPrototype(subType,superType){ var prototype = Object(superType.prototype); prototype.constructor = subType; subType.prototype = prototype; }
相关文章推荐
- node.js javascript理解原型继承
- JS 关于原型和闭包的理解
- 一个简单的例子理解在JS原型继承中原型链是如何运作的
- 理解JS原型以及实现继承
- js核心基础之理解原型对象以及原型继承(三)
- JS高级知识(面向对象,原型,原型链理解,继承)
- 关于js原型和继承的方法复习
- JS继承机制的深入理解--动态原型存在的问题与解决
- js核心基础之理解原型对象以及原型继承(一)
- 【web前端-理解js原型】理解Javascript中的原型对象、原型链和继承
- js原型、原型链与继承的理解
- 深入理解JS原型链与继承
- 关于js原型继承
- 关于js原型链 原型的个人理解
- js中原型,原型链,原型链继承的个人理解
- JavaScripy关于对继承原型链,借用构造函数和组合继承的理解
- 关于js中,原型对象,原型链,构造函数,实例之间关系的理解与区别
- 分享一个关于js原型链的理解
- 对于js原型和原型链继承的简单理解(第一种,原型链继承)
- 关于js原型继承