Use of the Apply method in JS

Source: Internet
Author: User

1, the object of inheritance, the general practice is to replicate: Object.extend

The prototype.js is implemented in the following ways:

Object.extend = function (Destination,source) {//destination: Destination for object in     source} {//property: Property           Destination[property] = Source[property];    }             return destination;    }

In addition, there is a way, is function.apply (of course, the use of Function.call is also possible)

The Apply method can hijack another object's method, inheriting another object's properties

Function.apply (Obj,args) method can receive two parameters

OBJ: This object will replace the This object in the function class

Args: This is an array, which is passed as a parameter to function (args---arguments)

The Apply model code is as follows:

<script> function Person (name,age) {this.name = name;        This.age = age;        This.sayhello = function () {alert (' Hello ')}} function Print () {this.funcname = "print";             This.show = function () {var msg = [];//call: ["Name:tom", "age:13", "Funcname:print", "Grade:6", "School: Tsinghua Primary School"] For a (var key in this) {//Call, this means: Student,name:tom age:13 grade:6 ... if (typeof (This[key])! = "function") {Msg.push ([Key, ":", This[key]].join (""));        Join ("") puts all the elements in the array into a string}} console.log (Msg.join ("")); }} function Student (name,age,grade,school) {person.apply (this,arguments);//this-Student, arguments-        0: "Tom" 1:13 2:6 3: "Tsinghua Primary School" print.apply (this,arguments);        This.grade = grade;    This.school = School;        } var p1 = new Person ("Jake", 10);        P1.sayhello (); var S1 = new Student (' Tom ', 13, 6, "Tsinghua SmallLearning ");        S1.show ();        S1.sayhello ();         Alert (s1.funcname);</script>

The student class does not come with any method, but after person.apply (this,arguments), he has the SayHello method and all the attributes of the person class.

The show () method is automatically obtained after print.apply (this,arguments)

2, using the parameter array of apply to improve the function.apply () in improving program performance skills

Let's start with the Math.max () function, the Math.max can be followed by any parameter, and finally the maximum value in all parameters is returned. Like what:

Alert (Math.max (5,8)); 8

Alert (Math.max (5,7,9,3,1,6)); 9

But in many cases, we need to find the largest element in the array.

var arr = [5,7,9,1];

Alert (Math.max (arr)); This is not going to work. It must be written like this.

function Getmax (arr) {    var arrlen = arr.length;      for (var i=0,ret = arr[0]; i<arrlen; i++) {        ret = Math.max (Ret,arr[i]);      }    return ret;}

It's troublesome and inefficient to write. If you use apply, look at the code:

<script>    function GetMax2 (arr) {        return Math.max.apply (Null,arr);//arr-  to  0:5  1:7 2:9  3:1    }    var arr = [5,7,9,1];    Console.log (GETMAX2 (arr));</script>

Both ends of the code have achieved the same goal, but GETMAX2 lacks elegance, efficiency, and simplicity.

Another example is the push method of the array.

var arr1 = [1,3,4];

var arr2 = [3,4,5];

If we want to expand the arr2, and then append to the arr1, and finally let arr1 = [1,3,4,3,4,5];

Arr1.push (ARR2) obviously not. Because doing so will get [1,3,4,[3,4,5]]

We can only use one loop to push one (or Arr1.concat (ARR2)), but the Concat method does not change arr1 itself.

var Arrlen = Arr2.length;for (var i=0; i<arrlen; i++) {    arr1.push (arr2[i]);  }

It's been so easy since I got the Apply

Array.prototype.push.apply (ARR1,ARR2);

Transferred from: http://www.cnblogs.com/delin/archive/2010/06/17/1759695.html#undefined

Use of the Apply method in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.