zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    访问者模式
    oracle触发器简单实用示例
    C#控件交互效果类(也可以用作缩小面板放大,展示更多信息)
    23种设计模式探索C#
    windows快捷操作个人记录(常用)
    C#巧妙使用关键字async/await
    学习的枚举类型,结构以及初步了解数组
    目前学习.net时间让我摸不着头脑的事情
    对C#中几个循环语句的使用,请教
    学习了用控制台显示结果
  • 原文地址:https://www.cnblogs.com/aSnow/p/8873253.html
Copyright © 2011-2022 走看看