The difference between call apply in JavaScript

Source: Internet
Author: User

obj.call(thisObj, arg1, arg2, ...);obj.apply(thisObj, [arg1, arg2, ...]);

Both have the same effect, which is to bind obj (this) to Thisobj, when Thisobj has the properties and methods of obj. Or, Thisobj "inherits" the properties and methods of obj.

The only difference is that apply accepts an array parameter, and call accepts a continuous parameter.


function add(j, k){    return j+k;}function sub(j, k){    return j-k;}

We run on the console:


add(5,3); //8add.call(sub, 5, 3); //8add.apply(sub, [5, 3]); //8sub(5, 3); //2sub.call(add, 5, 3); //2sub.apply(add, [5, 3]); //2

With call and apply, we can implement object inheritance. Example:


var Parent = function(){    this.name = "yjc";    this.age = 22;}var child = {};console.log(child);//Object {} ,空对象Parent.call(child);console.log(child); //Object {name: "yjc", age: 22}

The above implements the inheritance of the object.

The difference between call apply in JavaScript

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.