printName(18) // tom 18 printName.call(p, 28) // jack 28
Bind
1 2 3 4 5 6 7 8 9 10 11 12
let p = { name: 'jack' }
functionf() { console.log(this.name) }
let f1 = f.bind(p)
f1() // jack
Apply
1 2 3 4 5 6 7 8 9 10 11 12 13
let p = { name: 'jack' }
functionf() { console.log(this.name) }
f.call(p) // jack
f.apply(p) // jack
The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is “A for array and C for comma.”
With arrow functions there are no binding of this.
With arrow functions the this keyword always represents the object that defined the arrow function.
1 2 3
(() =>console.log(this))() // prints Window in browser, which defined the global arrow function // prints {} in node.js, which is the same as a global this
this in Vue
1 2 3 4 5 6 7 8 9 10 11 12 13
<template />
<script> exportdefault { data: () => ({ d: this// this gives undefined }), methods: { f1 () { console.log(this) }, // prints current Vue component f2: () =>this// this gives undefined } }; </script>