zoukankan      html  css  js  c++  java
  • js中的继承

    1、原型继承

    原型继承的特点:即继承了父类的模版,又继承了父类的原型对象

    // 父类
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    // 父类的原型对象方法
    /*Person.prototype.say = function() {
        console.log('hello');
    }*/
    
    Person.prototype = {
        constructor: Person,
        say: function (){
            console.log(this.name)
        }
    }
    
    // 子类
    function Boy(sex) {
        this.sex = sex;
    }
    Boy.prototype = new Person('zn',18);
    var b = new Boy();
    console.log(b.name);
    console.log(b.age);
    b.say();

    2、类继承(只继承模版, 不继承原型对象) (借用构造函数的方式继承)

    // 父类
    function Person(name, age) {
        this.name = name;
        this.age  = age;
    }
    // 父类的原型对象属性
    Person.prototype.id = 1;
    
    // 子类
    function Boy(name, age, sex) {
        // call apply
        Person.call(this, name, age);
        this.sex = sex;
    }
    var b = new Boy('张三', 20, '男');
    console.log(b.name);
    console.log(b.age);
    console.log(b.sex);
    console.log(b.id);

    3、混合继承(借用构造函数继承 + 原型继承)

    // 父类
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    Person.prototype.id = 1;
    
    Person.prototype = {
        constructor: Person;
        sayName: function () {
        console.log(this.name);
    }
    }
    // 子类
    function Boy(name, age, sex) {
        // 借用构造函数继承
        Person.call(this, name, age);
        this.sex = sex;
    }
    // 原型继承
    //继承父类的原型对象
    Boy.prototype = new Person();
    var b = new Boy('zn', 18, '男');
    console.log(b.name);
    console.log(b.sex);
    console.log(b.age);
    b.sayName();

    4、ES5 提供的create方法 在实际开发过程中为了兼容低版本浏览器做出继承方法如下封装

    var create = function(obj) {
        //(火狐 谷歌等)
        if (Object.create) {
            return Object.create(obj);
        }
        else {
            //(ie 低版本)
            function F() {}
            F.prototype = obj;
            return new F();
        }
    }
  • 相关阅读:
    23. CTF综合靶机渗透(十六)
    1.7 xss之同源策略与跨域访问
    6.wireshark使用全解
    29.极具破坏力的DDoS:浅析其攻击及防御
    6.【转载】业务安全漏洞挖掘归纳总结
    28.【转载】挖洞技巧:APP手势密码绕过思路总结
    27.【转载】挖洞技巧:如何绕过URL限制
    WordPress整站轻松开启HTTPS
    观复嘟嘟观古今
    房价会下跌么?
  • 原文地址:https://www.cnblogs.com/goweb/p/5660925.html
Copyright © 2011-2022 走看看