Javascript call and apply, javascriptapply

Source: Internet
Author: User

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.

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.