JS中的继承
来源:互联网 发布:linux怎么新建文件 编辑:程序博客网 时间:2024/06/09 21:19
一、原型继承
function surperClass () { this.name= 'hello';}surperClass.prototype.getSurperName = function(){ return this.name;};function subClass(name){ this.name = 'world';}//继承了surperClasssubClass.prototype = new surperClass();subClass.prototype.getsubClassName = function(){ return this.name;};var instance = new subClass();console.log(instance.getSurperName); //hello
原型链虽然很强大,可以用它来实现继承,但它也存在一些问题。在通过原型来实现继承时,原型实际上会变成另一个类型的实例。于是,原先的实例也就顺理成章地变成了现在的原型属性了
二、借用构造函数继承
function surperClass(name){ this.name = name; this.color = ['red','white','yellow'];}function subClass(){ surperClass.call(this,'goodnight');}var instance = new subClass();instance.push('blue');alert(instance.color); // red ,white,yellow ,bluevar instance2 = new subClass();alert(instance2.color); // red white yellow
三、组合继承
function surperClass(name){ this.name = name; this.color = ['red','white','yellow'];}surperClass.prototype.getName = function(){ // body... return name;};function subClass(age){ surperClass.call(this,'goodnight'); this.age = age;}subClass.prototype = new surperClass();subClass.prototype.getAge = function(){ // body... return this.age;};var instance = new subClass(23);alert(instance.getName()); //goodnightalert(instance.getAge()); // 23
四、原型式继承
function object (o) { function f () { // body... } f.prototype = o; return new f();}var persion = { name:'nick', friends:['lily','Rob']}var anotherpersion = Object(persion);anotherpersion.name; //'nick'anotherpersion.friends.push('134');alert(persion.friends) //lily rob 134
五、寄生式继承
function object (o) { function f () { // body... } f.prototype = o; f.getName = function () { /* body... */ } return new f();}
六、寄生组合式继承
function inhreitProperty (subClass,surperClass) { // body... //复制一份父类的原型副本保存在P中 var p = object(surperClass.prototype); //修正因为重写子类原型导致子类的constructor属性被修改 p.constructor = subClass; //设置子类的原型 subClass.prototype = p;}
阅读全文
0 0
- JS 中的继承
- js中的继承实现
- js中的继承实现
- JS中的继承实现
- js中的继承实现
- JS中的继承
- js中的继承
- js中的继承
- js中的继承机制
- JS中的继承实现
- js中的继承
- JS中的继承
- Js中的继承
- js中的继承
- js中的继承
- JS 中的继承实现
- js中的继承
- js中的继承
- python隔离虚拟环境拷贝至服务器
- 让你自己编写的Android的Launcher成为系统中第一个启动应用程序
- 四大范围对比
- teamviewer
- ExtJS流程总结(一)
- JS中的继承
- DDD & Microservices
- python rabbitmq 延迟队列
- git flow常用命令
- BZOJ 3799 字符串重组 贪心模拟乱搞
- vi & vim
- static_cast、dynamic_cast、const_cast和reinterpret_cast总结
- 数据结构实验之链表九:双向链表
- 关于521