this and bind (this) (es5 new)

this与bind(this)

this

this points to the scope (object instance) this function, the following examples

const app = {
    name: 'xiaoming',
    log() {
      console.log(this.name);
    },
    child() {
      return {
        name: 'b',
        log() {
          console.log(this.name);
        },
      };
    },
  };
  app.log(); // xiaoming
  app.child().log(); // b

this detailed

- Global Environment

Whether the strict mode ( 'use strict'), the global execution environment (outside any function thereof) this point to the global object.

console.log(this === window); // true

this.name = 'react';
console.log(name); // react
console.log(window.name); // react

- within the function

Inside the function, the value of this depends on how the function is called.

1. ordinary function

Non-strict mode, this defaults to the global object.

function f() {
  return this;
}

// brower
f() === window;
// node
f() === global;

In strict mode, this default object instance pointing to the calling function.

function f() {
  'use strict'
  return this;
}
f() === undefined;
Because here f () is called directly, and not as an object property or method calls, such as window.f (), so that this here is undefined.

If the value of this in order to further spread from one environment, a method is necessary to apply a call or

var obj = {A: 'the Custom' }; 

// this property is defined in the global object. 
var A = 'Free Join' ; 

function whatsThis (Arg) {
   return  this II.A;   // called by a function of the value of this depends 
} 

whatsThis ();           // 'Free Join' 
whatsThis.call (obj);   // 'the Custom ' 
whatsThis.apply (obj); // ' the Custom '

JavaScript function definitions are inherited from Function, we can bind this value to a particular object by calling the Function.prototype properties in the call or apply methods.

function the Add (C, D) {
   return  the this II.A + the this .B + C + D; 
} 

var O = {A:. 3:. 1, B }; 

// Object first parameter is used as 'the this' 
/ / subsequent parameters passed as an argument to a function call 
add.call (O,. 5,. 7); // . 1. 5 + + +. 3 = 16. 7 
// first parameter is used as an object of 'the this' 
// second parameter is an array, as a function call parameter element array in 
add.apply (O, [10, 20 is]); // . 1 + 10 + 20 is =. 3 + 34 is

Use call and apply the function of time to pay attention, if the value passed to this is not an object, JavaScript will attempt to use ToObject internal operations to convert it to an object. Thus, if the values ​​such as a primitive value or 7 'foo', then the correlation will be used to convert it into a constructor object, the original value of 7 is converted to an object, like a new Number (7) Thus, the character string 'foo' is converted into new String ( 'foo') Thus, for example:

function bar () { 
  the console.log (Object.prototype.toString.call ( the this )); 
} 

// original value 7 is converted into an object implicitly 
bar.call (7); // [Number The Object]

2. Functions arrow

Arrow pointer function does not own this. When a method is called by a function call () or apply (), only transmission parameters (not bind this). In a closed lexical environment, this this function and a normal function coincides arrows; global code, this function is set to arrow global object.

var obj = { 
  bar: function () {
     var X = (() => this );
     return X; 
  } 
} 
// in the object obj to call bar (), so that this binding is obj 
var Fn = obj. bar (); 
the console.log (Fn () === obj); // to true 

// here and does not call bar (), but assigning reference bar fn2 
var Fn2 = obj.bar;
 // global variable to call bar (), so that this here binding global 
console.log (fn2 () () == window);

3. The function of the object

When the function is called in the subject, this point is the object to invoke the function.

const app = {
  name: 'xiaohong',
  f: function() {
    console.log(this.name);
  }
}

f () function where this points to the app object.

this binding only affected members of the closest reference. E.g:

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37

o.b = {g: independent, prop: 42};
console.log(o.b.g()); // 42

This proved to be a member of an object o has little to do with him, the closest reference is the most important.

This prototype chain

If the method exists in the prototype chain of an object, then this point is to call this method the object, as the same way as on the object.

var o = {
  f: function() { 
    return this.a + this.b; 
  }
};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5

In this case, the object p f does not belong to its own property, it's f property is inherited from its prototype. Although the discovery process to f, the final is to find properties in f o, this does not matter; the discovery process from the first reference pf the beginning, so the function of this point p. That is, since f p as a method call, so it's this point to p.

in this getter and setter
as getter or setter function will put this object bound to set or get property.

the bind (the this)
ES5 introduces Function.prototype.bind. Call f.bind (someObject) and creates a function f has the same scope and function of the body, but in this new function, this will permanently bound to bind the first parameter, no matter how the function is to be call. bind binding parameters take effect only once

function F () {
   return  the this II.A; 
} 

var G = f.bind ({A: "AZERTY" }); 
the console.log (G ()); // AZERTY 

var H = g.bind ({A: ' Yoo '}); // the bind take effect only once! 
the console.log (H ()); // AZERTY

Incoming bind the second parameter and the following, in accordance with the order of the configuration parameter binding function.

var foo = {
    x: 3
} 
var bar = function(){
    console.log(this.x);
} 
bar(); // undefined

var boundFunc = bar.bind(foo);

boundFunc(); // 3

Sometimes, we need to keep this in context, that is, in a runtime environment, you want access to this value. At what point have to do it?

Let's say the method of assigning an object to a global variable, and then call this approach in a global variable, then this value is no longer the original object but a window object. But we also need to call in accordance with the method of the object.

Another example, a method includes the closure, the closure is not accessible to this target its external function, since this subject is automatically generated when you call your own methods, internal search function only when these two variables searches for an object to its own activities. Without searching out the scope along the chain, so that the closure can not access functions outside this value.

In react, often see

export default class App extends Component {
  constructor(props) {
    super(props);
    this.foo = this.foo.bind(this);
  }
  
  foo() {
    // todo something
  }
  
  render() {
    return (
      <View>
        <Button onPress={this.foo()}/>
      </View>
    )
  }
}

If you pass a function name to a variable, then parentheses after the variable '()' to call this method, then this method of internal points will be lost. Inside the foo method which will be outside of this point will be lost.

To solve this problem, we need to instantiate an object at the time, we need to bind in the constructor this, so that no matter how the event handler passed, it's this point are fixed, fixed point we are instantiated object.

Original link: https: //blog.csdn.net/u013003052/article/details/87894194

Guess you like

Origin www.cnblogs.com/yangwenbo/p/11447333.html