Application scenarios of call apply in javascript

  • 2020-05-30 19:25:42
  • OfStack

Often see something similar in 1 some jQuery plug-in callback. call xxx, xxx) although the book has said call and apply function can change the scope, but still not very thorough understanding of the changing scope mainly to solve the problem, is there any alternatives, or what 2 function mainly in order to solve this problem, application scenarios, when to use the most appropriate, each time to read such code is dizzy, 1 following jump out from the linear reading, feel a little round

The purpose of call and apply is simply to change the context. There are too many applicable scenarios, though sometimes just for the sake of "aesthetics".

1.

Object.prototype.toString.call(Obj)

To determine the type of Obj

Although arguments is similar to Array, it doesn't have push of Array, what should it do?
Array.prototype.push.call(arguments)

3.Javascript has no concept of private methods and wants to be implemented with closures


(function () {
  var Person = function () {
    this.doSomeThing = function () {
      _privateFunction.call(this);
    }
  }

  var _privateFunction = function () {

  }

  window.Person = Person;

}).call(window);

That's pretty much what it means. When you use callback, when you want the context in your callback to be the current context, you can also use call or apply. What's the benefit?

At this point, this in your callback refers to the current context. For example, there is a class Person, and then his method say has an callback parameter. If the callback is executed through ordinary parentheses, then the other methods executing person in callback need to be implemented with person.other, but after context switching, this.other.


var Person = function(){

};

Person.prototype.say = function(callback){
  callback();
};

Person.prototype.other = function(){

};

var vincent = new Person();

vincent.say(function(){
  vincent.other();
});

call:


var Person = function(){

};

Person.prototype.say = function(callback){
  callback.call(this);
};

Person.prototype.other = function(){

};

var vincent = new Person();

vincent.say(function(){
  this.other();
});

That's all for this article, I hope you enjoy it.


Related articles: