分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

js继承

发布时间:2023-09-06 01:45责任编辑:顾先生关键词:js

主要有原型链、借助构造函数、组合继承、原型式继承、寄生式继承、寄生组合继承6种,但是由于原型链、构造函数、原型式继承、寄生继承都有一定的缺点,并不常用,故此不在赘述。

  • 组合继承
function super(name) { ???this.name = name; ???this.colors = ["red","blue"]; ???}super.prototype.sayName = function(){ ???alert(this.name);};function sub(name,age){ ???super.call(this,name); //属性继承 ?第二次调用super() ???this.age = age;}sub.prototype = new super(); //方法继承 第一次调用super()sub.prototype.sayAge = function(){ ???alert(this.age);};var instance1 = new sub("Barney",32);instance1.colors.push("balck");alert(instance1.colors);//red blue blackinstance1.sayName();//Barneyinstance1.sayAge();//32var instance1 = new sub("Ted",33);alert(instance1.colors);//red blueinstance1.sayName();//Tedinstance1.sayAge();//33

如上所示,两个实例之间的白能量并没有互相影响,而且都可以使用super和sub中的方法,但是super()被调用了两次,显得有些多余,所以有了原型式继承

  • 寄生组合继承
    function inheritPrototype(subType,superType){ ???var prototype = Object(superType.prototype); ???prototype.constructor = subType; ???subType.prototype = prototype;}function super (name){ ???this.name = name; ???this.colors = ["red","blue"];}super.prototype.sayName = function(){ ???alert(this.name);};function sub(name,age){ ???super.call(this,name); ???this.age = age;}inheritPrototype(sub,super);sub.prototype.sayAge = function(){ ???alert(this.age);};var instance = new sub("Barney",32);instance.sayName();//Barneyinstance.sayAge();//32
    instance instanceof super; //false 不知道为什么会是false
    instance instanceof sub; //true

js继承

原文地址:https://www.cnblogs.com/171220-barney/p/8558714.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved