call([thisObj[,arg1[, arg2[, [,.argN]]]]])
- thisObj (optional): it’s object which can be act as currently
- arg1, arg2, argN (optional) : the parameters which can be passed to the method.
The call method can be used to instead of another object to invoke a method. It can change the object context of a function to a new object which thisObj referenced.
Note: The thisObj is a optional parameter, it will reference to Global object if it is not provided. And the
call method is only used by
Let’s use fake code to explain it firstly. see below code:
The functionality of call method is that obj2 is able to invoke the method1 of obj1 with arg1, arg2 parameters.
Let’s see a simple example:
1 2 3 4 5 6 7 8 9
The value of result variable is 3, not -1. Because the sub function object has been insteaded by add function object. So the
add.call(sub, 1, 2) actually is
Okay, so let’s see a little complex example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
This will print the ‘class two’ message in the console window of browser. You can execute above code fragment to check it.
In this example, the classTwo object doesn’t have showMesage function, but he want to display his message, so he can invoke classOne’s with
So far, maybe you will think we can use the
call function to simulate the
OOP. You are right, let’s get the example.
1 2 3 4 5 6 7 8 9 10 11 12 13
So the MyClass inherites the BaseClass. The
BaseClass.call(this) that means using the object of BaseClass to instead of this object. So the MyClass can access the property and function of BaseClass.