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

Detailed explanation of this attribute in JavaScript

零到壹度
Release: 2018-04-08 14:28:59
Original
2710 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template