Home  >  Article  >  Web Front-end  >  Application scenarios of call apply in javascript_javascript skills

Application scenarios of call apply in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:03:431085browse

We often see something like callback.call(xxx,xxx) in some jQuery plug-ins. Although I read in the book that the call and apply functions can change the scope, I still can’t fully understand the main purpose of changing the scope. What problems are solved, are there any alternatives, or what problems are these two functions mainly intended to solve, application scenarios, and when is the most appropriate time to use them? Every time I read code like this, I get dizzy and jump out of linear reading. It feels a bit convoluted

The function of call and apply is very simple, which is to change the context. There are too many applicable scenarios. Although sometimes it is just for "beauty", the following are the ones I commonly use.

1.

Copy code The code is as follows:
Object.prototype.toString.call(Obj)

Used to determine the type of Obj

Although arguments are similar to Array, they do not have Array’s push method. What should I do?
Array.prototype.push.call(arguments)

3.Javascript does not have the concept of private methods, so I want to use closures to implement it

(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 calling back, when you want the context in your callback to be the current context, you can also use call or apply. What are the benefits?

At this time, this in your callback refers to the current context. For example, a class Person, and its method say has a callback parameter. If this callback is executed through ordinary brackets, then other methods of person executed in this callback need to be implemented using person.other, but the context is switched. After that, it’s all done with this.other~ The code comparison is as follows:

var Person = function(){

};

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

Person.prototype.other = function(){

};

var vincent = new Person();

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

Used 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();
});

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn