In-depth understanding of this in ECMA Javascript (with examples)
This article brings you an in-depth understanding of this in ECMA Javascript (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
This is actually a binding that occurs when the function is called. What it points to depends entirely on where the function is called (that is, how the function is called).
Four rules: (JS you don’t know)
1. Default binding
function foo() { console.log( this.a ); } var a = 2; foo(); // 2
whether strict or not mode, in the global execution context (outside any function body) this refers to the global object. (MDN)
In strict mode, this will retain its value when it enters the execution context. If this is not defined by the execution context, it will remain undefined. (MDN)
function foo() { "use strict"; console.log( this.a ); } var a = 2; foo(); // TypeError: this is undefined
2. Implicit binding/loss
When functions are called as methods in objects, their this is the object that calls the function, and the binding is only affected by The influence of the closest member reference. (MDN)
//隐式绑定 function foo() { console.log( this.a ); } var obj2 = { a: 42, foo: foo }; var obj1 = { a: 2, obj2: obj2 }; obj1.obj2.foo(); // 42
//隐式丢失 function foo() { console.log( this.a ); } function doFoo(fn) { // fn 其实引用的是 foo fn(); // <-- 调用位置! } var obj = { a: 2, foo: foo }; var a = "oops, global"; // a 是全局对象的属性 doFoo( obj.foo ); // "oops, global"
3. Display binding
If you want to pass the value of this from one context to another, you must use the call or apply method. (MDN)
Calling f.bind(someObject) will create a function with the same function body and scope as f, but in this new function, this will be permanently bound to the first parameter of bind. No matter how this function is called.
var obj = { count: 0, cool: function coolFn() { if (this.count < 1) { setTimeout( function timer(){ this.count++; // this 是安全的 // 因为 bind(..) console.log( "more awesome" ); }.bind( this ), 100 ); // look, bind()! } } }; obj.cool(); // 更酷了。
Hard binding
Create a wrapper function that passes in all parameters and returns all values received.
Hard binding will greatly reduce the flexibility of the function. After using hard binding, you cannot use implicit binding or explicit binding to modify this.
// 简单的辅助绑定函数 function bind(fn, obj) { return function() { return fn.apply( obj, arguments ); }; }
Soft binding
Specify a global object and a value other than undefined for the default binding, then you can achieve the same effect as hard binding while retaining implicit binding or explicit binding. The ability of binding to modify this.
Function.prototype.softBind = function(obj) { var fn = this; var curried = [].slice.call( arguments, 1 );// 捕获所有 curried 参数 var bound = function() { return fn.apply( (!this || this === (window || global))?obj : this curried.concat.apply( curried, arguments ) ); }; bound.prototype = Object.create( fn.prototype ); return bound; };
4. new binding
When a function is used as a constructor (using the new keyword), its this is bound to the new object being constructed. (MDN)
Use new to call a function, or when a constructor call occurs, the following operations will be automatically performed (JS you don’t know)
Create (or construct ) a completely new object.
This new object will be connected by performing [[ prototype ]].
This new object will be bound to this of the function call.
If the function returns no other object, then the function call in the new expression will automatically return this new object.
function foo(a) { this.a = a; } var bar = new foo(2); console.log( bar.a ); // 2
Four rules priority
new Binding> Explicit Binding> Implicit Binding> Default Binding
-
Is the function called in new (new binding)? If so, this is bound to the newly created object.
var bar = new foo()
Copy after login -
Is the function called via call, apply (explicit binding) or hard binding? If so, this is bound to the specified object.
In addition: If binding null or undefined, the default binding rules are actually applied.var bar = foo.call(obj2)
Copy after login -
Is the function called in a context object (implicitly bound)? If so, this is bound to that context object.
var bar = obj1.foo()
Copy after login -
If neither, use the default binding. If in strict mode, it is bound to undefined , otherwise it is bound to the global object.
var bar = foo()
Copy after loginAmong them: Indirect reference functions will apply the default binding rules
function foo() { console.log( this.a ); } var a = 2; var o = { a: 3, foo: foo }; var p = { a: 4 }; o.foo(); // 3 (p.foo = o.foo)(); // 2
Copy after login
Exceptions
1. Arrow function
The arrow function does not use the four standard rules of this, but determines this based on the outer (function or global) scope.
In arrow functions, this is consistent with the this of the enclosing lexical context. (MDN)
Arrow functions inherit the this binding of the outer function call (no matter what this is bound to). This is actually the same mechanism as self = this.
The binding of arrow functions cannot be modified.
2. nodejs
setTimeout(function() { console.log(this) //浏览器中:window //nodejs中:Timeout实例 }, 0)
Other explanations
https://www.zhihu.com/questio...
func(p1, p2) is equivalent to
func.call(undefined, p1, p2)
obj.child.method(p1, p2) is equivalent to
obj.child .method.call(obj.child, p1, p2)
If the context you pass is null or undefined, then the window object is the default context (the default context in strict mode is undefined)
Example
var number = 50; var obj = { number: 60, getNum: function () { var number = 70; return this.number; } }; alert(obj.getNum()); alert(obj.getNum.call()); alert(obj.getNum.call({number:20}));
The above is the detailed content of In-depth understanding of this in ECMA Javascript (with examples). For more information, please follow other related articles on the PHP Chinese website!

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

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

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text
