Home Web Front-end JS Tutorial The pointer of this in JS and the functions of call and apply

The pointer of this in JS and the functions of call and apply

Oct 08, 2018 pm 04:25 PM
apply this

This article shares with you the basic JS content this pointer and the related knowledge points of call and apply. Friends who are interested can learn and refer to it.

In specific practical applications, the point of this cannot be determined when the function is defined, but is determined when the function is executed. It can be roughly divided into the following three types according to the execution environment:

1. When a function is called as a normal function, this points to the global object

2. When a function is called as a method of an object, this points to the object

3. When the function is called as a constructor, this points to the newly created object

Example 1:

window.name = 'myname';
function getName() {
  console.log(this.name);
}
getName(); //输出myname
Copy after login

Example 2:

var boy = {
  name: 'Bob',
  getName: function() {
    console.log(this.name);
  }
}
boy.getName(); //输出Bob
Copy after login

Example 3:

function Boy(name) {
  this.name = name;
}
var boy1 = new Boy('Bob');
console.log(boy1.name); //输出Bob
Copy after login

For Example 3, there is another special case, that is, when the constructor returns an object through "return" At that time, the final result of this operation returns this object, not the newly created object, so this is of no use in this case.

Example four:

function Boy(name) {
  this.name = name;
  return { //返回一个对象
    name: 'Jack'
  }
}
var boy1 = new Boy('Bob');
console.log(boy1.name); //输出Jack
Copy after login

Example five:

function Boy(name) {
  this.name = name;
  return 1; //返回非对象
}
var boy1 = new Boy('Bob');
console.log(boy1.name); //输出Bob
Copy after login

call and apply The role of

apply accepts two parameters. The first parameter specifies the pointer of this in the function body. The second parameter is an array or array-like used to pass the called function. parameter list.

Example 1:

function getInfo() {
  console.log(this.name+' like '+arguments[0]+' and '+arguments[1]);
}
var boy1 = {
  name: 'Bob',
  age: 12
}
getInfo.apply(boy1,['sing','swimming']); //输出Bob like sing and swimming
Copy after login

call The number of parameters passed in is not fixed. The same as apply, the first parameter is also used to specify The point of this in the function body, starting from the second parameter, each parameter is passed to the called function in turn.

Example 2:

function getInfo() {
  console.log(this.name+' like '+arguments[0]+' and '+arguments[1]);
}
var boy1 = {
  name: 'Bob',
  age: 12
}
getInfo.call(boy1,'sing','shopping'); //输出Bob like sing and shopping
Copy after login

In addition, most advanced browsers also implement the bind method. The difference between it and call and apply is that bind only changes the function Internal this points to, but it will not be executed immediately, you need to call it explicitly.

Example 3: Simulate the browser's bind method

Function.prototype.bind = function(obj){
  var self = this;
  return function(){
    return self.apply(obj,arguments);
  }
};
var obj = {
  name: 'Bob',
  age: 12
};
var func = function(){
  console.log(this.name+' like '+arguments[0]+' and '+arguments[1]);
}.bind(obj);
func('sing','shopping');
Copy after login

Missing this

In some cases, the pointing of this will be lost. At this time, we need to use call, apply and bind to change the pointing of this.

Example 1: When the "getName" method is called as a property of the "boy" object, this points to the "boy" object. When another variable refers to the "getName" method, because it is used as a normal function call, so this points to the global object window

var boy = {
  name: 'Bob',
  getName: function() {
    console.log(this.name);
  }
}
boy.getName(); //输出Bob
var getBoyName = boy.getName;
getBoyName(); //输出undefined
Copy after login

Example 2: Even if the function is defined inside the function, if it is called as a normal object, this also points to the window object

var boy1 = {
  name: 'Bob',
  age: 12,
  getInfo: function() {
    console.log(this.name);
    function getAge() {
      console.log(this.age);
    }
    getAge();
  }
}
boy1.getInfo(); //Bob
        //undefined
Copy after login

The above is the content of this chapter All content, for more related tutorials please visit JavaScript Video Tutorial!

The above is the detailed content of The pointer of this in JS and the functions of call and apply. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Example analysis of Java Fluent Mybatis aggregation query and apply method process Example analysis of Java Fluent Mybatis aggregation query and apply method process May 22, 2023 pm 01:31 PM

Data preparation: In order to aggregate the conditions of the query, several pieces of data are added. MIN we try to get the minimum age. Method implementation @OverridepublicIntegergetAgeMin(){Mapresult=testFluentMybatisMapper.findOneMap(newTestFluentMybatisQuery().select.min.age("minAge").end()).orElse(null);returnresult!=null?Convert.toInt(result.get (&qu

Let's talk about why Vue2 can access properties in various options through this Let's talk about why Vue2 can access properties in various options through this Dec 08, 2022 pm 08:22 PM

This article will help you interpret the vue source code and introduce why you can use this to access properties in various options in Vue2. I hope it will be helpful to everyone!

An article that understands this point and catches up with 70% of front-end people An article that understands this point and catches up with 70% of front-end people Sep 06, 2022 pm 05:03 PM

A colleague got stuck due to a bug pointed by this. Vue2’s this pointing problem caused an arrow function to be used, resulting in the inability to get the corresponding props. He didn't know it when I introduced it to him, and then I deliberately looked at the front-end communication group. So far, at least 70% of front-end programmers still don't understand it. Today I will share with you this link. If everything is wrong If you haven’t learned it yet, please give me a big mouth.

Clever way to use this keyword in jQuery Clever way to use this keyword in jQuery Feb 25, 2024 pm 04:09 PM

Flexible use of this keyword in jQuery In jQuery, the this keyword is a very important and flexible concept. It is used to refer to the DOM element currently being manipulated. By rationally using this keyword, we can easily operate elements on the page and achieve various interactive effects and functions. This article will combine specific code examples to introduce the flexible use of this keyword in jQuery. Simple this example First, let's look at a simple this example. Suppose we have a

What is this? An in-depth analysis of this in JavaScript What is this? An in-depth analysis of this in JavaScript Aug 04, 2022 pm 05:02 PM

What is this? The following article will introduce you to this in JavaScript, and talk about the differences between this in different calling methods of functions. I hope it will be helpful to you!

How to use this method in Java How to use this method in Java Apr 18, 2023 pm 01:58 PM

1. this keyword 1. Type of this: Which object is called is the reference type of that object 2. Usage summary 1. this.data;//Access attribute 2. this.func();//Access method 3.this( );//Call other constructors in this class 3. Explanation of usage 1.this.data is used in member methods. Let us see what will happen if this is not added classMyDate{publicintyear;publicintmonth;publicintday; publicvoidsetDate(intyear,intmonth,intday){ye

How does JavaScript change this pointer? Brief analysis of three methods How does JavaScript change this pointer? Brief analysis of three methods Sep 19, 2022 am 09:57 AM

How does JavaScript change this pointer? The following article will introduce to you three methods of changing this pointer in JS. I hope it will be helpful to you!

Detailed explanation of this in JavaScript arrow function Detailed explanation of this in JavaScript arrow function Jan 25, 2024 pm 01:41 PM

The arrow function in JavaScript is a relatively new syntax. It does not have its own this keyword. On the contrary, the this of the arrow function points to the scope object containing it. The impacts are: 1. This in the arrow function is static; 2. Arrow Functions cannot be used as constructors; 3. Arrow functions cannot be used as methods.

See all articles