[TOC]

Basic knowledge of

This is a frequently used object in JavaScript. By definition, in Javascript this always refers to the object on which it was called, and this will refer to whoever made the call.

Here are some examples to guide you through this

This in the global case

function test () {
    console.log(this)
}
test()
Copy the code

Output the window object directly, because JS will find this pointing to undefined when searching, so JS will point this to the window.

"use strict"
function test () {
    console.log(this)
}
test()
Copy the code

In strict mode, JS does not refer this to the window, so the output is undefined.

Call this in case of this

var obj = {
    name:'hero'
}
function test () {
    console.log(this)
}
obj.test = test
obj.test()
Copy the code

This code nicely shows that by whom this is called,this will be referred to the caller’s object.

Now let’s think about this situation.

var obj = {
    name:'hero'.proxy: {name:'proxy hero'}}function test () {
    console.log(this)
}
obj.proxy.test = test
console.log('obj.proxy.test')
obj.proxy.test()

var _p = obj.proxy
console.log('_p.test')
_p.test()
Copy the code

This is not what you expected

obj.proxy.test
{name: "hero", proxy: {name: "proxy hero".testThe {name: : ƒ}} _p"proxy hero".test: ƒ}
Copy the code

but

obj.proxy.test
{name: "proxy hero".testThe {name: : ƒ} _p"proxy hero".test: ƒ}
Copy the code

This example shows that the binding of this is only affected by the most recent member. So this is bound to the proxy.

This call, the apply and bind

var obj = {
    name:'hero',
    test (postString) {
        console.log(this,postString)
    }
}
var obj2 = {name:'super hero'}
obj.test.call(obj2,'call')
obj.test.apply(obj2,['apply'])
Copy the code

The mechanism of call and apply is the same, which directly modify the internal reference of this. The only difference is that call is passed arguments one by one, while apply is passed an entire array of arguments.

var obj = {
    name:'hero',
    test (postString) {
        console.log(this,postString)
    }
}
var obj2 = {name:'super hero'}
obj.test.bind(obj2)('bind')
Copy the code

The mechanism of bind is different from that of the other two. To run, it needs to be executed normally. This is used a lot in React.

In the ES6 proposal, you can also bind in this way.

// The function binding operators are two colons (::) side by side
var k = obj2::obj.test
k('::bind')
Copy the code

For now, only Babel supports this proposal.

The resources

Developer.mozilla.org/zh-CN/docs/…