假设我有一个这样的变量:
var a = this.property || this.parent.anotherProperty;
是否可以为
a
设置上下文(按上下文,我的意思是“ this”,也许“ scope”是一个更好的词...),就像对函数使用.call()
或.apply()
一样?编辑:
我有一个给定值返回的辅助函数:
如果值是一个函数-> value()
如果不是函数->值
这是代码:
function unwrapValue(value){
return typeof value === 'function' ? value() : value;
}
unwrapValue在一个普通对象(Utils)内部,并且从该对象外部调用:
Utils.unwrapValue(value);
现在,我在函数中有一个属性
url
(可以是函数,也可以是其他东西):this.url = this.baseUrl || this.collection.baseUrl;
我不知道this.url是一个函数还是其他东西,所以我使用unwrapValue来获取url的值:
var params = {};
params.url = Utils.unwrapValue(this.url);
问题就在这里,unwrapValue返回this.url,但将“ this”设置为其他值(我相信这是Utils对象,但由于某种原因,它是
window
对象),所以params.url
是window.baseUrl || window.collection.baseUrl
而不是我想要。如果
value
是一个函数,我可以这样解决:function unwrapValue(value, context){
if(typeof value === 'function'){
return typeof context === 'undefined' ? value() : value.call(context);
}else{
return value;
}
}
因此,如果将第二个参数
context
传递给unwrapValue
,则值的this
将设置为context
。带着这个问题,我正在寻找一种方法来使用
context
aslo,以防value
不是像这样的函数:this.url = this.baseUrl || this.collection.url;
只是要澄清一点:this.baseUrl和this.collection.url是简单的字符串
有办法解决吗?
最佳答案
您可能希望将对象常量thisthis传递给该函数:
function fn() {
var a = this.a || this.parent.a;
console.log(a);
}
fn.call({
a: false,
parent: {
a: "foobar"
}
});
由于您不再传递其他参数,因此也可以使用
apply
代替call
。