search
HomeWeb Front-endJS TutorialIn-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(); // <h2 id="Display-binding">3. Display binding</h2><p>If you want to pass the value of this from one context to another, you must use the call or apply method. (MDN)<br>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. </p><pre class="brush:php;toolbar:false">var obj = {
    count: 0,
    cool: function coolFn() {
    if (this.count <h3 id="Hard-binding">Hard binding</h3><p>Create a wrapper function that passes in all parameters and returns all values ​​received. <br>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. </p><pre class="brush:php;toolbar:false">// 简单的辅助绑定函数
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)

  1. Create (or construct ) a completely new object.

  2. This new object will be connected by performing [[ prototype ]].

  3. This new object will be bound to this of the function call.

  4. 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

  1. Is the function called in new (new binding)? If so, this is bound to the newly created object.

     var bar = new foo()
  2. 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)
  3. Is the function called in a context object (implicitly bound)? If so, this is bound to that context object.

     var bar = obj1.foo()
  4. 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()

    Among 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

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools