• js继承的方式


    原型链继承

     function Parent(){
                this.name='mike';
                this.age=12;
              }
              function Child(){
                
              }
              //儿子继承父亲(原型链)
              Child.prototype=new Parent();//Child继承Parent,通过原型形成链条
              var test=new Child();
              console.log(test.age);
              console.log(test.name);//得到被继承的属性
              //孙子继续原型链继承儿子
              function Brother(){
                this.weight=60;
              }
              Brother.prototype=new Child();//继承原型链继承
              var brother=new Brother();
              console.log(brother.name);//继承了Parent和Child,弹出mike
              console.log(brother.age);//12
               console.log(brother.weight);
               //instanceof 就是判断一个实例是否属于某种类型
              console.log(brother instanceof Child);//ture
              console.log(brother instanceof Parent);//ture
              console.log(brother instanceof Object);//ture

    call和apply函数的继承

    call和apply都可以实现函数的继承

    function Parent(age){
                this.name=['mike','jack','smith'];
                this.age=age;
              }
              function Child(age){
               Parent.call(this,age);//让Child拥有Parent的属性
               Parent.apply(this,[age]);
              }
              var test=new Child(21);
              console.log(test.age);//21
              console.log(test.name);
              test.name.push('bill');
              console.log(test.name);//mike,jack,smith,bill

    call和apply的区别是穿的参数不同

    call和apply都接收两个参数,第一个参数都是thisobj

    apply的第二个参数必须是有效数组或arguments对象

    call的第二个参数必须列举出来

    var myObject = {firstName:'my', lastName:'Object'};
    
            function getMessage(sex,age){
                console.log(this.firstName + this.lastName + " 性别: " + sex + " age: " + age );
            }
             getMessage.apply(myObject,["未知",22]);//myObject 性别: 未知 age: 22
              getMessage.call(myObject,"未知",22);//myObject 性别: 未知 age: 22
  • 相关阅读:
    PAT2019顶级7-2:美丽的序列(线段树+DP)
    ZOJ2112 Dynamic Rank(可持久化线段树套树状数组)
    CF1353E K-periodic Garland(动态规划)
    CF1353D Constructing the array(优先队列)
    HDU2069 Coin Change(基础DP)
    surf(树状数组+DP)
    双倍快乐(回文树)
    ZOJ3591 Nim(博弈论)
    HDU6601 Keep On EveryThing But Triangle(可持久化线段树)
    HDU6599 I Love Palindrome String(回文树)
  • 原文地址:https://www.cnblogs.com/aSnow/p/8873253.html
Copyright © 2020-2023  润新知