


Methods to change this pointer in JS (call, apply, bind)_javascript skills
This is a keyword in JavaScript. The value of this will change as the function is used in different situations. But there is always a principle, that is, this refers to the object that calls the function.
This generally points to the current callee, but it can also be changed in other ways. Three methods will be introduced below:
1. When used as inheritance:
function Parent(age){ this.name=['mike','jack','smith']; this.age=age; } function Child(age){ Parent.call(this,age);//把this指向Parent,同时还可以传递参数 } var test=new Child(21); console.log(test.age);//21 console.log(test.name); test.name.push('bill'); console.log(test.name);//mike,jack,smith,bill
2. Both call and apply can change this to point to , but the second parameter of apply is a hash distribution, and call can be an array
console.log(Math.max.apply(null,[1,2,3,4]));//4
apply() method receives two parameters: one is the scope in which to run the function, and the other is the parameter array. Among them, the second parameter can be an instance of Array or an arguments object. The call() method has the same effect as the apply() method, they only differ in the way they receive parameters. For call()
As far as methods are concerned, the first parameter's this value does not change. What changes is that the remaining parameters are passed directly to the function. In other words, when using the call() method, the parameters passed to the function must be enumerated one by one.
3.ES5 also defines a method : bind(), which will create an instance of a function, and its this value will be bound to the bind() function value. Such as
window.color='red'; var o={color:'blue'}; function sayColor(){ console.log(this.color); } var objectSaycolor=sayColor.bind(o); //var objectSaycolor=sayColor.bind(); objectSaycolor();//blue
Here sayColor() calls bind() and passes in the object o, creating the objectSayColor() function. The this value of the objectSayColor() function is equal to o, so even if this function is called in the global scope, you will see blue.
The above is the method that the editor introduces to you to change this pointer in JS (call, apply, bind). I hope it will be helpful to you!
I still have some time to add some basic knowledge to you: the difference between call() and apply()
1. Definition of method
call method:
Syntax: call(thisObj, Object)
Definition: Call a method of an object to replace the current object with another object.
Instructions:
The call method can be used to call a method on behalf of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj.
If no thisObj parameter is provided, the Global object is used as thisObj.
apply method:
Syntax: apply(thisObj, [argArray])
Definition: Apply a method of an object to replace the current object with another object.
Description:
If argArray is not a valid array or is not an arguments object, a TypeError will be caused.
If neither argArray nor thisObj are provided, the Global object will be used as thisObj and no parameters can be passed.
Code example:
function Animal(name) { this.name = name; this.showName = function() { console.log(this.name); }; } function Cat(name) { Animal.call(this, name); } Cat.prototype = new Animal(); function Dog(name) { Animal.apply(this, name); } Dog.prototype = new Animal(); var cat = new Cat("Black Cat"); //call必须是object var dog = new Dog(["Black Dog"]); //apply必须是array cat.showName(); dog.showName(); console.log(cat instanceof Animal); console.log(dog instanceof Animal);
Simulate call, replace this with apply
function Animal(name) { this.name = name; this.showName = function() { alert(this.name); }; }; function Cat(name) { this.superClass = Animal; this.superClass(name); delete superClass; } var cat = new Cat("Black Cat"); cat.showName();

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of the picture and uses jQuery to calculate the average color of each area. Then, use

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.
