search
HomeWeb Front-endJS TutorialDetailed explanation of this attribute in JavaScript

Detailed explanation of this attribute in JavaScript

Apr 08, 2018 pm 02:28 PM
javascriptthisAttributes

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

Result: "Name: Li Si"

Look at another example:

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

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;

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

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

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

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

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

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

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

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

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

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

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);

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

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

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);

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.

Solution:

var print = d.getTime.bind(d);

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

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

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
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment