javaScript的难度开头---使用call方法和apply方法

javaScript  的组合继承

1,使用  call  方法

      定义:调用一个对象的一个方法,以另一个对象替换当前对象。

<!DOCTYPE html>
<html>
  <head>
    <title>借用构造函数</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=gbk">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <script type="text/javascript">
    	function Humans(name){
    		this.name=name;
    		this.clothing=["夹克","尼龙外套","运动袜套"];
    	}
    	function Man(nama,age){
    		Humans.call(this,name);//借用构造函数的属性
    		this.age=age;
    	}
    	Man.prototype=new Humans();//继承Humans函数
    	
    	var man1=new Man("那盘",23);
    	man1.clothing.push("皮袍");
    	alert(man1.clothing);     //输出:"夹克","尼龙外套","运动袜套","皮袍"
    	
    	var man2=new Man("马呐喊",34);
    	alert(man2.clothing);     //输出:"夹克","尼龙外套","运动袜套"
    
    
    </script>
  </body>
</html>

2,apply   方法

     定义:应用某一对象的一个方法,用另一个对象替换当前对象。

<script type="text/javascript">
      /*定义一个人类*/
      function Person(name,age)
      {
          this.name=name;
          this.age=age;
      }
     /*定义一个学生类*/
     functionStudent(name,age,grade)
     {
       Person.apply(this,arguments);
         this.grade=grade;
    }
    //创建一个学生类
        var student=new Student("qian",21,"一年级");
     //测试
     alert("name:"+student.name+"
"+"age:"+student.age+"
"+"grade:"+student.grade);
     //大家可以看到测试结果name:qian  age:21  grade:一年级
     //学生类里面我没有给name和age属性赋值啊,为什么又存在这两个属性的值呢,
     //这个就是apply的神奇   之处.
</script>

  

     分析: Person.apply(this,arguments);

               this:在创建对象在这个时候代表的是student

                     arguments:是一个数组,也就是[“qian”,”21”,”一年级”];

                   也就是通俗一点讲就是:用student去执行Person这个类里面的内容,在Person这个类里面存在this.name等之类的语句,这样就将属性创建到了student对象里面

3,

    什么情况下用apply,什么情况下用call

   在给对象参数的情况下,如果参数的形式是数组的时候,比如apply示例里面传递了参数arguments,这个参数是数组类型,并且在调用Person的时候参数的列表是对应一致的(也就是       Person和Student的参数列表前两位是一致的) 就可以采用 apply , 如果我的Person的参数列表是这样的(age,name),而Student的参数列表是(name,age,grade),这样就可以用call来实现了,也就是直接指定参数列表对应值的位置(Person.call(this,age,name,grade));

原文地址:https://www.cnblogs.com/bb1008/p/7073240.html