The purpose of the apply (or call) method in JavaScript----inheritance of objects

Source: Internet
Author: User

All along, my understanding is that the function.apply (or Function.call) method in JS is to change the function's execution context (Excute context), in other word, to change the scope of the function at execution time,

The most immediate is the value that affects this predefined variable.!! Function.apply (obj, arguments) is the change function execution environment for the incoming obj object, that is, Funtion internal this will be changed to obj.

The following example is a search for someone else's example.

Let's look at an example.

function Person (name,age,grade) {   //define a class, human      this.name=name;     Name      this.age=age;       Age     this.sayhello=function () {alert (grade)}, function Student (name,age,grade,school) {    //Student class     Person.apply (this,arguments); for (var i in arguments) {alert (arguments[i])}        This.grade=grade;                Grade     This.school=school;                 School} stu = new Student (' Yuanshao ', +, ' university ', ' Huaqiao ') Stu.sayhello ();//So Stu has the SayHello () method in the person constructor.

Explain:

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)

Let's look at an example:

Alert (Math.max (5,8,9,11))   //8 can ———————————— var arr=[5,7,9,1]alert (Math.max (arr))    //This is not possible. —————————————————————— var Arr=[5,7,9,1]alert (Math.max.apply (Null,arr))    //This is OK. It must be written like this.

  

The purpose of the apply (or call) method in JavaScript----inheritance of objects

Related Article

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.