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)

不言
不言forward
2018-11-24 14:05:592259browse

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)

  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.com. If there is any infringement, please contact admin@php.cn delete