如果我有这个json结构:
var j = {
param1: 'hello',
param2: 'world',
func: function() {
console.log(this.param1 + ' ' + this.param2);
}
};
Run Code Online (Sandbox Code Playgroud)
thisin func未定义.如何在这个json对象中访问self?谢谢
编辑:
我正在尝试:
j.func();
Run Code Online (Sandbox Code Playgroud)
this取决于函数的调用方式.要回答你的问题,我们需要看看你是如何被召唤的func().
如果你打电话:
j.func()
Run Code Online (Sandbox Code Playgroud)
然后,this里面func将被设置为j.
如果你func()直接调用(如果你j.func作为一个回调传递然后被其他函数直接调用会发生什么),那么this可能会被设置为window或者undefined取决于你是否处于严格模式.例如:
function callme(callback) {
// the context of `j` will be lost here and
// this will just call func() directly without setting this to j
callback();
}
callme(j.func);
Run Code Online (Sandbox Code Playgroud)
this也可以由调用者通过使用j.func.apply()或j.func.call()允许调用者指定所需值来显式设置this.
| 归档时间: |
|
| 查看次数: |
480 次 |
| 最近记录: |