How to convert value to string
you have three ways Converting a value to string in JavaScript
- String(value)
- “” + value
- value.toString()
value.toString is the worst. It doesn’t always work. So don’t use it. I personally use String(value) or “” + value
How to use this (hard binding in javascript)
this is a binding that is defining in function invocation time. Where the function is invoke that environment variables will be binded to this
For instance in node.js we have such code. The this value define its invocation environment
index.js
1 2 3 4 5 6 7 |
function foo() { console.log(this.a) } var a = 10 foo() // undefined |
we’ve got undefined because in there this is bind to the global scope and in our example var a = 10 related to the local scope of the file index.js. it seems like that. That’s why we got undefined, To get 10 we have to bind a to the global this without var typing a = 10 then we will get 10
Hard bind is a way where we bind functions to the object explicitly. Let’s look at the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function foo() { console.log(this.a) } let obj = { a: 10 } var myF = function() { foo.call(obj) } myF() // 10 setTimeout(myF, 100) // 10 |
We call it “hard binding” no the myF function is hard bound to the obj. Everytime we call the myF it the this will have variables from of obj this
the end