FE.ES-understand this of ECMA Javascript

This is actually the 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 do n’t know)

1. Default binding

function foo() {
    console.log( this.a );
}
var a = 2;
foo(); // 2

Whether in strict mode or not, in the global execution context (outside of any function body) this refers to the global object. (MDN)
In strict mode, this will keep the value when he entered the execution context. If this is not defined by the execution context, then 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 an object, their this is the object that called the function, and the binding is only affected by 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, regardless of this function How it was 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 wrapped function, pass in all the parameters and return all the values ​​received.
Hard binding will greatly reduce the flexibility of the function. After using hard binding, you cannot modify this by using implicit binding or explicit binding.

// 简单的辅助绑定函数
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 the ability to modify this implicitly or explicitly.

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 are automatically performed (JS you do n’t know)

  1. Create (or construct) a completely new object.
  2. This new object will be executed [[prototype]] connection.
  3. This new object will be bound to this in the function call.
  4. If the function does not return other objects, the function call in the new expression will automatically return the 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 by call, apply (explicit binding) or hard binding? If so, this binds the specified object.
    In addition: if null or undefined is bound, the default binding rule is actually applied.

     var bar = foo.call(obj2)
    
  3. Is the function called in some context object (implicit binding)? If so, this is bound to that context object.

     var bar = obj1.foo()
  4. If not, 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: the indirect reference function 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

exception

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 the arrow function, this is consistent with this in the closed lexical context. (MDN) The
arrow function will inherit the this binding of the outer function call (no matter what this is bound to). This is actually the same as the self = this mechanism.
Arrow function bindings cannot be modified.

Chapter 2

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) 等价于
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}));

Reference material: In-
depth understanding of JavaScript series (13): This? Yes, this!
MDN-this
"You do n’t know JS on the volume" read the small note of setTimeout this points to the problem Script
JavaScript this principle-Ruan Yifeng
how to understand JavaScript The this keyword? -Fang Yinghang-Know about
JS this related issues

This article is reproduced in: Ape 2048 FE.ES-this understanding ECMA Javascript

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12738255.html