Apply, Call contrast

apply、call

In order to change the call and apply Context is present, i.e. directed to change the internal function

javascript context is a major feature in the presence of defined function, the concept of context and context changeable runtime

apply, call this point may be varied, i.e. can not in this object

However, when using a method other object has a method you want

apple.say.call(banana);
apple.say.apply(banana);
//两者都可获得banner中的方法

Difference between the two

However, the same effect of both methods accept different parameters, call parameters are placed in incoming order, apply the parameters will be placed in an array

Examples

apply two arrays may be used as additional

Array.prototype.push.apply(array1,array2)

max method call in the Math function

var  numbers = [5, 458 , 120 , -215 ]; 
var maxInNumbers = Math.max.apply(Math, numbers),   //458
    maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215); //458

Verify arrays (provided toString () method is not overridden)

functionisArray(obj){ 
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}

Class (pseudo) array using array

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));

There is an object called a pseudo-array structure in Javascript. A special feature is the arguments object, as well as calling getElementsByTagName, document.childNodes like, they return NodeList object belongs to pseudo-array. Applications can not push, pop or the like in the Array.
But we can Array.prototype.slice.call converted into real objects with an array length property, so you can domNodes all methods applied under the Array.

example

Define a log method so that it can proxy console.log method, a common solution is:

function log(msg) {
  console.log(msg);
}
log(1);    //1
log(1,2);    //1

The above method can solve the most basic needs, but when the number of parameters passed is the time of uncertainty, the above method becomes ineffective, this time you can consider using the apply or call, pay attention to where the number of arguments passed is uncertain the , the use of the best apply, as follows:

function log(){
  console.log.apply(console, arguments);
};
log(1);    //1
log(1,2);    //1 2

The next requirement is to add to each message a log "(app)" of the prefix, for example:

log("hello world"); //(app)hello world

? How to do this when you need it more elegant think of arguments parameter is a pseudo-array, by Array.prototype.slice.call into a standard array, and then use the array method unshift, like this:

function log(){
  var args = Array.prototype.slice.call(arguments);
  args.unshift('(app)');
 
  console.log.apply(console, args);
};

bind

Before discussing the bind () method Let's look at a topic:

var altwrite = document.write;
altwrite("hello");

The results: Uncaught TypeError: Illegal invocation
altwrite () function to change or global window object this point, leading to abnormal call prompt illegal execution, the right solution is to use bind () method:

altwrite.bind(document)("hello")

Of course, also possible to use call () method:

altwrite.call(document, "hello")

Binding function

bind()The simplest use is to create a function, the function calls no matter how this all have the same value. Common mistakes like the example above, the method from the object out, then call and want this point to the original object. If you do not do special treatment, usually lose the original object. Use bind () method can be very beautiful solution to this problem:

this.num = 9; 
var mymodule = {
  num: 81,
  getNum: function() { 
    console.log(this.num);
  }
};

mymodule.getNum(); // 81

var getNum = mymodule.getNum;
getNum(); // 9, 因为在这个例子中,"this"指向全局对象

var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81

bind () method is very similar to apply and call, but also can be changed to point to this function in vivo.

MDN explanation is: bind () method creates a new function, called binding function, when calling the binding function, binding the first argument will be created when it passed bind () method as this the incoming bind () method of the second and subsequent parameter per se adding parameters as parameters in the order of the original function call to the function is to bind the original function.

Direct look at the specifics of how to use the monomer in common mode, we usually use _this, that, self preservation such as this, so that we can continue to refer to changing the context after it. like this:

var foo = {
    bar : 1,
    eventBind: function(){
        var _this = this;
        $('.someClass').on('click',function(event) {
            /* Act on the event */
            console.log(_this.bar);     //1
        });
    }
}

Since Javascript mechanisms specific, context in eventBind:. Function () {} transition to $ ( '. SomeClass') on ( 'click', function (event) {}) changed the use of variables to store this these methods are useful, there is no problem. Of course, using the bind () may be a more elegant solution to this problem:

var foo = {
    bar : 1,
    eventBind: function(){
        $('.someClass').on('click',function(event) {
            /* Act on the event */
            console.log(this.bar);      //1
        }.bind(this));
    }
}

Incoming In the above code, bind () creates a function, when the click event when the binding is called, it's this keyword is set to be passed in the value (in this case call bind () parameter). So, here we want to pass the context of this (in fact, foo), to bind (function). Then, when the callback function is executed, this would point to foo object. Again a simple chestnut:

var bar = function(){
console.log(this.x);
}
var foo = {
x:3
}
bar(); // undefined
var func = bar.bind(foo);
func(); // 3

Here's global scope when we create a new function func, when using the bind () function to create a binding, when it is executed, it is this will be set to foo, rather than as we call bar () .

Guess you like

Origin www.cnblogs.com/baiyang2292/p/11300723.html