Let’s say I have a variable like this:
var a = this.property || this.parent.anotherProperty;
It’s possible to set the context (by context i mean ‘this’, maybe the ‘scope’ is a better word…) for a like when using .call() or .apply() for functions?
EDIT:
I have an helper function that given a value return:
- if the value is a function -> value()
- if it isn’t a function -> value
This is the code:
function unwrapValue(value){
return typeof value === 'function' ? value() : value;
}
unwrapValue is inside a plain object (Utils) and it’s called from outside this object:
Utils.unwrapValue(value);
Now, I have a property url in a function (that may be either a function or something else):
this.url = this.baseUrl || this.collection.baseUrl;
I don’t know if this.url is a function or something else so I use unwrapValue to get the value of url:
var params = {};
params.url = Utils.unwrapValue(this.url);
And the problem is here, unwrapValue return this.url but setting ‘this’ to something else (i tought it was the Utils object but for some reason it’s the window object) so params.url is window.baseUrl || window.collection.baseUrl which is not what i want.
If value is a function I solved this way:
function unwrapValue(value, context){
if(typeof value === 'function'){
return typeof context === 'undefined' ? value() : value.call(context);
}else{
return value;
}
}
so that if a second parameter context is passed to unwrapValue, value’s this will be set to context.
with this question I was searching a way to use context aslo in the case value wasn’t a function like:
this.url = this.baseUrl || this.collection.url;
And just to clarify a little more: this.baseUrl and this.collection.url are simple strings
There’s a way to solve that?
You possibly want to pass an object literal as the thisArg into that function:
As you don’t pass in further arguments, you could’ve used
applyas well instead ofcall.