品易云推流 关闭
文章详情页
文章 > JavaScript > JavaScript有哪些继承的方法

JavaScript有哪些继承的方法

JavaScript继承

头像

小妮浅浅

2021-08-18 09:45:103090浏览 · 0收藏 · 0评论

1、寄生式继承,基于某个对象创建一个对象,然后增强对象,返回对象。

function create(original){
    // 通过调用函数创建一个新对象
    var clone = object(original);
    // 以某种方式增强对象
    clone.sayHi = function(){
        console.log('hi')
    }
    return clone;
}
var person = {
    name: 'chen'
}
var person1 = create(person);
person1.sayHi();

2、原型链继承,将父类的实例作为子类的继承。

function Parent(){
    this.name = 'parent'
}
Parent.prototype.sayName = function(){
    return this.name
}
function Child(){
}
// 继承了Parent
Child.prototype = new Parent();
var child1=new Child();
child1.say();

3、组合继承,使用原型链继承共享的属性和方法。

通过借用构造函数继承实例属性。

function Parent(name){
    this.name = name;
    this.arr = [1,2,3]
}
Parent.prototype.sayName = function(){
    console.log(this.name)
}
function Child(name,age){
    // 继承属性
    Parent.call(this, name)
    this.age=age
}
// 继承方法
Child.prototype = new Parent()
Child.prototype.constructor = Child;
Child.prototype.sayAge = function(){
    console.log(this.age)
}
var child1=new Child('chen',21);
child1.arr.push(4); //[1,2,3,4]
child1.sayName()    // 'chen'
child1.sayAge()     // 21
 
var child2=new Child('miao', 12)
child2.arr          // [1,2,3]
child2.sayName()    // "miao"
child2.sayAge()     // 12

以上就是JavaScript继承的方法,希望对大家有所帮助。更多Javascript学习指路:Javascript

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图