Chinaunix首页 | 论坛 | 博客
  • 博客访问: 153716
  • 博文数量: 42
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 399
  • 用 户 组: 普通用户
  • 注册时间: 2015-09-23 11:47
个人简介

程序猿啊程序猿

文章分类

全部博文(42)

文章存档

2016年(28)

2015年(14)

我的朋友

分类: JavaScript

2016-06-24 11:58:49


点击(此处)折叠或打开

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>call和apply</title>
  6. </head>
  7. <body>
  8.     <script>
  9.    //apply用法:劫持另一个对象的方法,继承另一个对象的属性 (object,[arguments])
  10.    //call用法: 劫持另一个对象的方法,继承另一个对象的属性(object,argument1,argument2,....) 二者的差别是参数传递的方式不同
  11.    function Person(user,age){
  12.       this.user=user;
  13.       this.age=age;
  14.    }

  15.    function Student(user,age,job){
  16.         Person.apply(this,arguments) //this继承了Person中的属性和方法,this代表了Student PS:注意参数的继承
  17.        this.job=job;
  18.    }
  19.    // var student=new Student('zhao','25','web');
  20.    // alert("name:"+student.user+" age:"+student.age+" job:"+student.job);

  21.    function Student1(user,job,age){
  22.        Person.call(this,age,user);
  23.        this.job=job;
  24.    }
  25.   // var student1=new Student('zhao','25','web');
  26.   // alert("name:"+student1.user+" age:"+student1.age+" job:"+student1.job)

  27.     function add(a,b){
  28.         alert(a+b);
  29.     }
  30.     function sub(a,b){
  31.         alert(a-b)
  32.     }
  33.     // sub.call(add,9,6) //3
  34.     // add.call(sub,9,6) //15 js中函数其实是对象,函数名是对Function对象的引用


  35.     // function Animal(){
  36.     //     this.name='dog';
  37.     //     this.showName=function(){
  38.     //         alert(this.name)
  39.     //     }
  40.     //     return this.showName
  41.     // }
  42.     // Animal()(); // 输出 dog


  43.        function Animal(){ //函数就是对象,有属性和方法
  44.            this.name='dog';
  45.            this.showName=function(){
  46.                alert(this.name)
  47.            }
  48.        }
  49.        function Cat(){
  50.            this.name='cat';
  51.        }
  52.        var ani=new Animal(); //继承了Animal的方法和属性
  53.        var cat=new Cat();
  54.        // ani.showName.call(cat); //输出 cat 就近原则 this.name='dog'被this.name='cat'覆盖 也可写成ani.showName.call(cat,'')
  55.        // ani.showName.apply(cat,[]);//输出 cat

  56.        //多重继承
  57.        function func1(){
  58.            this.showAdd=function(a,b){
  59.                alert(a+b)
  60.            }
  61.        }
  62.        function func2(){
  63.            this.showSub=function(a,b){
  64.                alert(a-b)
  65.            }
  66.        }
  67.        function func(){
  68.            func1.call(this);
  69.            func2.call(this);
  70.        }
  71.        var demo=new func(); //函数作为对象来引用,有方法和属性
  72.        // demo.showAdd(9,6);//15
  73.        // demo.showSub(9,6);//3
  74.     </script>
  75. </body>
  76. </html>

阅读(1509) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~