Home >Web Front-end >JS Tutorial >Detailed introduction to js call method (inheritance of js)_Basic knowledge
call method
See
Applies to: Function object
Requires
Version 5.5
Calls a method on an object, replacing the current object with another object.
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Parameters
thisObj
Optional. The object that will be used as the current object.
arg1, arg2, , argN
Optional. A sequence of method parameters will be passed.
Explanation
The call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj.
If no thisObj parameter is provided, the Global object is used as thisObj.
-------------------------------------------------- -----------------------------------------------
At first glance , it is easy to confuse people, let’s give some simple explanations first
obj1.method1.call(obj2, argument1, argument2)
As above, the function of call is to put the method of obj1 on obj2 and use it later. argument1.. These are passed in as parameters.
Give a specific example
add.call(sub,3,1);
Look at a slightly more complicated example
this.showNam = function()
{
alert(this.name);
}
}
function Class2()
{
this.name = "class2";
}
var c1 = new Class1();
var c2 = new Class2();
c1.showNam.call(c2);
How about it, you think it’s interesting, you can let object a execute the method of object b, which is something that java programmers dare not think of. What’s more interesting is that you can use call to implement inheritance
function Class2()
{
Class1.call(this);
}
var c2 = new Class2();
c2.showTxt("cc");
Yes, that’s it. This is how javaScript simulates inheritance in object-oriented and can also implement multiple inheritance.
function Class11()
{
this.showAdd = function(a,b)
{
alert(a b);
}
}
function Class2()
{
Class10.call(this);
Class11.call(this);
}