How to understand and skillfully use the JS in the call and apply?

Source: Internet
Author: User

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

Both of these functions are obj bound to (that is, this) to thisObj , this thisObj time have obj the properties and methods. Or, thisObj "inherited" obj properties and methods. Functions are executed immediately after binding.

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
Methods to invoke native objects

Example:

var a = {0:1, 1:"yjc", length: 2}; a.slice(); //TypeError: a.slice is not a functionArray.prototype.slice.call(a);//[1, "yjc"]

Object a resembles an array, but does not have methods such as the slice of an array. The slice method can be called when using call binding.

Implementing inheritance

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.

Use of BIND
obj.bind(thisObj, arg1, arg2, ...);

When you bind obj to Thisobj, Thisobj has the properties and methods of obj. Unlike call and apply, bind is not executed immediately after binding.

Same as Add () and sub ():

add.bind(sub, 5, 3); //不再返回8add.bind(sub, 5, 3)(); //8

If the first parameter of BIND is null or undefined, it is equal to binding this to the global object.

How to understand and skillfully use the JS in the call and apply?

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.