Home Web Front-end JS Tutorial Detailed explanation of this attribute in JavaScript

Detailed explanation of this attribute in JavaScript

Apr 08, 2018 pm 02:28 PM
javascript this Attributes

This article mainly introduces the this attribute in JavaScript. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

This always returns an object , that is, returns the property or method where is currently located object.

The properties of an object can be assigned to another object, so the current object where the properties are located is variable, that is, the point of this is variable.

eg:

var A = {
	name : '张三',
	describe : function(){
		return '姓名:' + this.name;
	}
};
var B = {
	name : '李四'
}
B.describe = A.describe;
B.describe();
Copy after login

Result: "Name: Li Si"

Look at another example:

var A = {
	name : '张三',
	describe : function(){
		return '姓名:' + this.name;
	}
};
var name = '李四'
f = A.describe;
f();
Copy after login

The result is also "Name: Li Si", because at this time this points to the object where f is running - the top-level window

Usage occasions of this

1. Global environment ——No matter whether this is inside the function or not, as long as it is run in the global environment, this refers to the top-level object window

2. Constructor ——Refers to the instance object

eg:

var Obj = function(p){
	this.p = p;
}
Obj.prototype.a = function(){
	return this.p;
}
var obj = new Obj('color');
obj.a();
obj.p;
Copy after login

The result is that "color" is returned

The above code defines a constructor Obj. Since this points to the instance object, defining this.p in Obj is equivalent to defining an instance object. p attribute, and then the m method can return this p attribute.

3. Object methods

var obj = {
	foo : function(){
		console.log(this);
	}
};
obj.foo();//obj
Copy after login

Only when the foo method is directly called on the obj object, this will point to obj. In other uses, this will point to the object where the code block is currently located.

Case 1: (obj.foo = obj.foo)()——window

Case 2: (false || obj.foo)()——window

Case 3: (1, obj.foo)()——window

In the above code, obj.foo is calculated first and then executed. Even if its value does not change, this no longer points to obj

4. Node

In Node, if it is in the global environment, this points to global, and in the module environment, this points to module.exports

Notes on using this

1. Avoid multiple layers of this

var o = {
	f1 : function(){
		console.log(this);
		var f2 = function(){
			console.log(this);
		}();
	}
}
o.f1();
Copy after login

The execution result is:

{f1: ƒ}

Window {decodeURIComponent: ƒ, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}

Why does this in f2 point to the global object? Because the execution process of the above code is actually

var temp = function(){
	console.log(this);
};
var o = {
	f1 : function(){
		console.log(this);
		var f2 = temp();
	}
}
o.f1();
Copy after login

Solution 1 - Use a variable pointing to the outer this in the second layer

var o = {
	f1 : function(){
		console.log(this);
		var that = this;
		var f2 = function(){
			console.log(that);
		}();
	}
}
o.f1();
Copy after login

Use a variable to fix the value of this , and then the inner layer calls this variable, which is a very useful and widely used method.

Solution 2 - Use strict mode. In strict mode, if this inside the function points to the top-level object, an error will be reported.

2. Avoid using this

var o = {
	v : 'hello',
	p : ['a1','a2'],
	f : function(){
		this.p.forEach(function(item){
			console.log(this.v + ' ' + item);
		});
	}
}
o.f();
Copy after login

in the array processing method. Result:

undefined a1

undefined a2

leads to this result. The reason is the same as the multi-layer this in the previous paragraph.

Solution one - use intermediate variables

var o = {
	v : 'hello',
	p : ['a1','a2'],
	f : function(){
		var that = this;
		this.p.forEach(function(item){
			console.log(that.v + ' ' + item);
		});
	}
}
o.f();
Copy after login

Solution two - treat this as the second parameter of the forEach method, fixed Its running environment

var o = {
	v : 'hello',
	p : ['a1','a2'],
	f : function(){
		this.p.forEach(function(item){
			console.log(this.v + ' ' + item);
		},this);
	}
}
o.f();
Copy after login

3. Avoid this in the callback function

var o = new Object();
o.f = function(){
	console.log(this === o);
}
o.f();//true
$("#button").on("click",o.f);//false
Copy after login

How to bind this

JavaScript provides call, apply, bind has three methods to switch/fix the pointer of this

function.prototype.call()

The call method of a function instance can specify the role of this when the function is executed. Domain, the parameter of the call method is an object. If the parameter is empty, null, or undefined, the global object will be passed in by default. If the call parameter is not an object, it will be automatically wrapped into a wrapping object. func.call(thisValue,arg1,arg2,...)

var n = 123;
var obj = {n : 456};
function a(){
	console.log(this.n);
}

a.call();//123
a.call(null);//123
a.call(undefined);//123
a.call(window);//123
a.call(obj);//456
Copy after login

An application of the call method is to call the native method of the object

var obj = {};
//原生方法
obj.hasOwnProperty('toString');//false
//覆盖了原生的方法
obj.hasOwnProperty = function(){
	return true;
}
obj.hasOwnProperty('toString');//true
//调回原生的方法
Object.prototype.hasOwnProperty.call(obj,'toString');//false
Copy after login

function.prototype.apply()

The only difference between apply and call is that apply accepts an array as a parameter when the function is executed, func.apply(thisValue,[arg1,arg2,...])

The application of apply One - Find the largest element of the array

var a = [10,3,4,2];
Math.max.apply(null,a);
Copy after login

Apply application two - Change the empty elements of the array to undefined (because the forEach method of the array will skip empty elements, but will not skip undefined) ?

var a = ['a','','b'];
function print(i){
	console.log(i);
}
a.forEach(print);//a b
Array.apply(null,a).forEach(print);//a undefined b
Copy after login

The running results are not the same as above, they are all a b

Apply application 3 - Convert array-like objects

Array.prototype.slice.apply({0:1,length:1});
Copy after login

Apply application 1 Four - the object of the bound callback function

var o = new Object();
o.f = function(){
	console.log(this === o);
}
var f = function(){
	o.f.apply(o);//或o.f.call(o);
}
$("#button").on("click",f);
Copy after login

function.prototype.bind()

bind method is used to bind this in the function body to an object and then return a new function

The following example will cause an error after assigning a value to the method

var d = new Date();
d.getTime();
var print = d.getTime;
print();//Uncaught TypeError: this is not a Date object.
Copy after login

Solution:

var print = d.getTime.bind(d);
Copy after login

bind is a step further than call and apply. In addition to binding this, it also You can bind the parameters of the original function

var add = function(x,y){
	return x * this.m + y * this.n;
}
var obj = {
	m:2,
	n:2
}
var newAdd = add.bind(obj,5);//绑定add的第一个参数x
newAdd(5);//第二个参数y
Copy after login

For those old browsers that do not support the bind method, you can define the bind method yourself

if(!('bind' in Function.prototype)){
	Function.prototype.bind = function(){
		var fn = this;
		var context = arguments[0];
		var args = Array.prototype.slice.call(arguments,1);
		return function(){
			return fn.apply(context,args);
		}
	}
}
Copy after login

The above is the detailed content of Detailed explanation of this attribute in JavaScript. 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)

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

bottom attribute syntax in CSS bottom attribute syntax in CSS Feb 21, 2024 pm 03:30 PM

Bottom attribute syntax and code examples in CSS In CSS, the bottom attribute is used to specify the distance between an element and the bottom of the container. It controls the position of an element relative to the bottom of its parent element. The syntax of the bottom attribute is as follows: element{bottom:value;} where element represents the element to which the style is to be applied, and value represents the bottom value to be set. value can be a specific length value, such as pixels

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Introduction to the attributes of Hearthstone's Despair Thread Introduction to the attributes of Hearthstone's Despair Thread Mar 20, 2024 pm 10:36 PM

Thread of Despair is a rare card in Blizzard Entertainment's masterpiece "Hearthstone" and has a chance to be obtained in the "Wizbane's Workshop" card pack. Can consume 100/400 arcane dust points to synthesize the normal/gold version. Introduction to the attributes of Hearthstone's Thread of Despair: It can be obtained in Wizbane's workshop card pack with a chance, or it can also be synthesized through arcane dust. Rarity: Rare Type: Spell Class: Death Knight Mana: 1 Effect: Gives all minions a Deathrattle: Deals 1 damage to all minions

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' 'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' Feb 25, 2024 pm 09:04 PM

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

See all articles