JavaScript有哪些继承的方法

325次阅读
没有评论

JavaScript有哪些继承的方法

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电脑。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:JavaScript2022-12-16发表,共计1278字。
新手QQ群:570568346,欢迎进群讨论 Python51学习