Despite the short syntax, getName()
is still just a regular function, which happens to be stored in an object. It does not carry an object reference around, this
is evaluated when/where/how you call it:
var obj1={
test:"This is obj1",
logTest(){console.log(this.test);}
};
obj1.logTest();
var fun=obj1.logTest;
fun();
var test="This is window"; // in browsers, regular variables on the top-level
fun();
window["test"]="Indeed it is"; // are actually members of window
fun();
this.test="All the same"; // really they are
fun();
var obj2={
test:"This is obj2",
testfun:fun
};
obj2.testfun();
//////////////////////////////////////
console.log("--------");
var boundfun=obj1.logTest.bind(obj1);
boundfun();
var obj3={
test:"This is obj3",
testfun:boundfun
};
obj3.testfun();
However the last part, boundfun()
, shows a method of function objects, bind()
which you can use to "pre-parametrize" a function, where the first parameter you can set is the this
. I also suggest checking the other two methods linked on the left side of that page, call()
and apply()
, both are about invoking a function via not just passing its arguments, but also freely setting this
. So you could create your own bindthis()
if you wanted to:
var obj1={
test:"This is obj1",
logTest(){console.log(this.test);}
};
function bindthis(fun,diz){
return function(){
fun.call(diz);
}
}
var boundfun=bindthis(obj1.logTest,obj1);
boundfun();
var obj2={
test:"This is obj2",
testfun:boundfun
};
obj2.testfun();
Side note: the question is not really about functional programming, this
is an object-oriented concept. So what you see is more like one particular mix of functional and object-oriented programming.