Start from scratch Web JS Advanced (iii) apply and Call,bind, closures and sandboxes

Source: Internet
Author: User

Hello everyone, here is "learn the Web series from scratch" and synchronize updates at the following address ...

  • Github:https://github.com/daotin/web
  • Public number: The top of the Web front
  • Blog Park: http://www.cnblogs.com/lvonve/
  • csdn:https://blog.csdn.net/lvonve/

Here I will start with the Web front End 0 Foundation, step-up learning web-related knowledge points, during the period will also share some fun projects. Now let's go to the Web Front end learning Adventure tour!

I. Apply and Call methods

Both Apple and call can change the this point in the function or method that called it.

The difference is that when you pass in a parameter, Apple has two parameters, the second is an array, and call starts with the second argument for all parameters of the function that called it.

How to use:

1, apply the use of the syntax:

Name of function. Apply (object, [Parameter 1, Parameter 2, ...]) ;

Method name. Apply (object, [Parameter 1, Parameter 2, ...]) ;

2, the use of call syntax:

Function name. Call (object, parameter 1, parameter 2, ...) ;

Method name. Call (object, parameter 1, parameter 2, ...) ;

1. function calls apply and call
function f1(x, y) {  console.log(x+y +this); // 这里面的this是window  return x+y;}var r1 = f1.apply(null, [10,20]); // 打印30 window,传入的是null,所以this指向还是windowconsole.log(r1); // 30var r2 = f1.call(null, 10,20);// 打印30 windowconsole.log(r2); // 30
//函数改变 this 的指向var obj = {};var r1 = f1.apply(obj, [10,20]); // 打印30 window,传入的是Obj,所以this指向是Objconsole.log(r1); // 30var r2 = f1.call(obj, 10,20);// 打印30 Objconsole.log(r2); // 30
2. Method calls apply and call
// 方法改变 this 的指向    function Person(age) {        this.age = age;    }    Person.prototype.eat = function () {        console.log(this.age); // this 指向实例对象    };    function Student(age) {        this.age = age;    }    var per = new Person(18);    var stu = new Student(20);    per.eat.apply(stu); // 打印 20    per.eat.call(stu); // 打印 20

Since the Eat method already points to Student, print 20 instead of 18.

Problem: We know that functions are also objects, and functions can call apple and calling methods, but these two methods are not in the instance function of this function object, so where is it?

Answer: All functions are instance objects of function, while apply and call are in the prototype object of the function constructor.

Second, bind method

Bind is a copy of the meaning, you can also change the call its function or method of this point, the parameters can be copied at the time of the transfer in, you can also be called after copying the time to pass in.

Use syntax:

1. Name of the function. Bind (object, parameter 1, parameter 2, ...); The return value is the copy of this function

2. Method name. Bind (object, parameter 1, parameter 2, ...); The return value is this method of replication

1. Function call bind
function f1(x, y) {    console.log(x + y + this);}// 1.参数在复制的时候传入var ff = f1.bind(null,10,20); // 这只是复制的一份函数,不是调用,返回值才是ff();// 2.参数在调用的时候传入var ff = f1.bind(null); // 这只是复制的一份函数,不是调用,返回值才是ff(10,20);
2. Method call Bind
function Person(age) {    this.age = age;}Person.prototype.eat = function () {    console.log(this.age); // this 指向实例对象};function Student(age) {    this.age = age;}var per = new Person(18);var stu = new Student(20);var ff = per.eat.bind(stu);ff(); // 20
Three, closure 1, the concept of closure package

There is a function or object B in function A, then the function or object B can access the data in function A, then the scope of function a becomes a closure.

2. Closure mode

Closure of the function pattern: functions are included in the function.

Closure in object mode: The function contains an object.

3, closure of the role

Cache data and extend the scope chain.

4. The advantages and disadvantages of closure package

is also the cached data, which results in a function within the scope of the closure.

5, closure of the application

Cached data, functions in the data, can be used outside.

If you want to cache data, put this data between the outer function and the inside function. This keeps calling the inner layer function, which is equivalent to the data in the outer function is not released in time, it is equivalent to caching the data.

// 函数闭包function A() {    var num = 10;    return function () {        return num++;    }}var func = A();console.log(func());console.log(func());console.log(func());
// 对象闭包function A() {    var num = 10;    return {        age: num++    };}var func = A();console.log(func.age);
Four, sand box

Sandbox: A small piece of the real environment, what happens inside does not affect the outside. Same operation, the same data will not collide with the outside.

Role: Avoid naming conflicts.

For example, self-invoking functions are equivalent to a sandbox environment.

(function (){        }());
V. Distinguishing between pseudo-arrays and true arrays
// 真数组    var arr = [10,20,30];    // 伪数组    var obj = {        0:10,        1:20,        2:30,        length: 3    };    // 真数组的访问    for(var i=0; i<arr.length; i++) {        console.log("真数组的访问:"+arr[i]);    }    // 伪数组的访问    for(var j=0; j<obj.length; j++) { // 错误:对象中没有length方法        console.log("伪数组的访问:"+obj[j]);    }

Method One, use length to distinguish

So it looks like the real array and the pseudo-array are indistinguishable.

But the length of the true array can be changed, pseudo-arrays can not, seemingly can be distinguished.

But, you remember a arguement. The length of this pseudo-array (object) can be changed, and method one distinguishes between failures.

Method two, using the method of the array ForEach to identify

Because each array is an instance object of array, and ForEach is in the prototype object of array, other pseudo-arrays are not available. Method two succeeded.

Start from scratch Web JS Advanced (iii) apply and Call,bind, closures and sandboxes

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.