Javascript call and apply, javascriptapply
Ref: http://www.cnblogs.com/fighting_cp/archive/2010/09/20/1831844.html
1. call () and apply () all belong to Function. prototype is implemented internally by the JavaScript engine because it belongs to Function. prototype, so each Function object instance, that is, each method has the call and apply attributes, that is, each Function contains two non-inherited methods: apply () and call (), and the function is the same.
2. Different parameters, such as: foo. call (this, arg1, arg2, arg3) = foo. apply (this, arguments) = this. foo (arg1, arg2, arg3)
Case 1:
Var name = 'window name'; test1 (); // The window name is displayed. this in test1 is the window object function test1 () {alert (this. name);} var obj = {name: 'obj name'} test1.call (obj); // In the obj name test, this is obj, the parameter is null by default // test1.apply (obj) and call are the same result alert (JSON. stringify (obj); // you can see that obj does not have the test1 function.
The magic of call and apply is that obj can call the test1 function, but does not have this function.
Case 2:
<Span style = "white-space: pre"> </span> function Animal (name) {this. name = name; this. showName = function () {alert (this. name) ;}}; function Cat (name) {Animal. call (this, name);} // Cat. prototype = new Animal (); function Dog (name) {Animal. call (this, name);} // Dog. prototype = new Animal (); // it can be understood that Dog inherits Animalvar cat = new Cat ("Black Cat"); var dog = new Dog (["Black Dog"]); cat. showName (); // Black Catdog. showName (); // Blcak Dogalert (cat instanceof Animal); // falsealert (dog instanceof Animal); // false returns true if you release the code commented out by the preceding two lines
The constructors in Javascript allow cat and dog to directly call the animal constructor during construction.