- In Javascript,
thisvalue is unstable. It depends on howthiscalls. Also it's different behavior innon-static modeandstatic mode. - call(), apply() and bind() use to stabilize
thisvalue in a function.
- Function.name
- Function.length
- Function.prototype.toString()
name
function test(){
console.log(this);
}
console.log(test.name);//testlength
function test(param1, param2){
console.log(this);
}
console.log(test.length);//2Add a property
function asim(param1, param2){
console.log(this);
}
asim.moo = 1;
console.log(asim.name);Function.toString()
function asim(param1, param2){
console.log(this);
}
console.log(asim.toString());
//function asim(param1, param2){
// console.log(this);
// }function asim(){
console.log(this);
}
asim.call(); //Window object
asim(); // Window object"use strict";
function asim(){
console.log(this);
}
asim.call(); // undefined"use strict";
function asim(){
console.log(this);
}
asim.call({}); // Object{}"use strict";
function asim(){
console.log(this);
}
asim.call(1); //1"use strict";
var asim = {
checkThis: function(){
console.log(this); //asim object
function checkOther(){
console.log(this); //undefined
}
checkOther();
}
}
asim.checkThis();"use strict";
var asim = {
checkThis: function(){
console.log(this); //asim object
function checkOther(){
console.log(this); //asim object
}
checkOther.call(this);
}
}
asim.checkThis();"use strict";
function a(b,c,d){
console.log(this); //1
console.log(b); //2
console.log(c); //3
console.log(d); //4
}
a.call(1,2,3,4);"use strict";
function a(b,c,d){
console.log(this); //1
console.log(b); //2
console.log(c); //3
console.log(d); //4
}
a.apply(1,[2,3,4]);Why might you use call why I use apply? Normally you would use call unless the function takes a variable number of parameters.
function sum(){
var total = 0;
for(var i=0; i<arguments.length; i++){
total += arguments[i];
}
return total;
}
var x = sum(1,2,3);
console.log(x);//6function sum(){
var total = 0;
for(var i=0; i<arguments.length; i++){
total += arguments[i];
}
return total;
}
var x = sum.call(null, 1,2,3);
console.log(x);//6function sum(){
var total = 0;
for(var i=0; i<arguments.length; i++){
total += arguments[i];
}
return total;
}
var things = [1,2,3,4,53,2,4,5,6,1];
var x = sum.apply(null, things);
console.log(x);//81- bind must use the function expression
var a = function(){
console.log(this);
}.bind(1);
a();//1
a();//1
a();//1var a = function(){
console.log(this);
}.bind(1);
var asim = {
func: a
}
asim.func(); //1Example - bind() doesn't work the declaring a function. it only works with function expression.
function a(){
console.log(this);
}.bind(1); // Syntax Error
"use strict";
var asim = {
checkThis: function(){
console.log(this); //asim object
var checkOther = function(){
console.log(this); // asim object! - not "undefined"
}.bind(this);
checkOther();
}
}
asim.checkThis();