Detailed explanation of this attribute in JavaScript
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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
