Table of Contents
2. Implicit binding/loss
3. Display binding
Hard binding
Soft binding
4. new binding
Home Web Front-end JS Tutorial In-depth understanding of this in ECMA Javascript (with examples)

In-depth understanding of this in ECMA Javascript (with examples)

Nov 24, 2018 pm 02:05 PM
css html5 javascript

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
Copy after login

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
Copy after login

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
Copy after login
//隐式丢失
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"
Copy after login

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(); // 更酷了。
Copy after login

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 );
    };
}
Copy after login

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;
};
Copy after login

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
Copy after login

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()
    Copy after login
  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)
    Copy after login
  3. 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
  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()
    Copy after login

    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
    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)
Copy after login

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}));
Copy after login

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

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.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

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.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

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

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

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.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

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.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

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

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

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 bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

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

See all articles