Home > Web Front-end > JS Tutorial > Usage of call(), apply()

Usage of call(), apply()

一个新手
Release: 2017-10-12 10:02:08
Original
1256 people have browsed it

1, call() and apply() are used to change this points to, the difference is that the parameter list is different(The former is a continuous parameter, the latter is a parameter array)

2, method definition:

      function.apply(thisObj[, argArray])
        function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);
Copy after login

Specially, when no parameters are passed, function.call() is quite To execute this function

3, example:

Because apply() and # The ##call() methods have the same effect, so here we take call() as an example, apply() Similarly:


 //定义一个Car的构造函数
      function Car(name,height){
            this.name=name;
             this.height=height;
         }

     function Maserati(name,age,height,width){
           this.name=name;
           this.age=age;
           this.height=height;
           this.width=width;
      }
  可以发现这里函数2包含了函数1的所有属性,即是继承的意思
       因此函数2这里可以用call()方法改写成
      function Maserati(name,age,height,width){
           Car.call(this,name,age);//此处this就是指向Maserati,此时Maserati就拥有Car的所有属性和方法了。
          this.height=height;
         this.width=width;
       }
   var a=new Maserati("maserati",23,188,98);
Copy after login
The following results are obtained:


The above is the detailed content of Usage of call(), apply(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template