我有一些问题围绕着JavaScript中的对象实例化和范围...
查看此示例代码:
someOtherObj = {
aMethod: function() {
$('body').append('aMethod successfully called!<br>');
return 'd';
}
}
// THIS WORKS!!
$('body').append(someOtherObj.aMethod() + '<br>');
someObj = {
aValue: 'a',
bValue: 'b',
cValue: this.aValue, // THIS DOESN'T WORK!!
dValue: new someOtherObj(), // THIS DOESN'T WORK!!
eValue: {
fValue: aValue, // THIS DOESN'T WORK!!
gValue: this.aValue, // THIS DOESN'T WORK!!
hValue: someObj.aValue, // THIS DOESN'T WORK!!
},
};
// JavaScript crashes out before this, but...
// This should result in: 'a'
$('body').append(someObj.cValue + '<br>');
// This should result in: 'd'
$('body').append(someObj.dValue.aMethod() + '<br>');
// These should result in: 'a'
$('body').append(someObj.eValue.fValue + '<br>');
$('body').append(someObj.eValue.gValue + '<br>');
$('body').append(someObj.eValue.hValue + '<br>');
我认为这些评论非常自我解释......但话虽如此:
cValue
参考(===
)aValue
,和/或具有与{{==
相同的值(aValue
) 1}}?答案 0 :(得分:-1)
我的理解是this
依赖于执行上下文。此外,它不能用于任务。换句话说:
var obj0 = {
self: this // <--refers to the global object
}
var obj1 = {
'use strict'
self: this // undefined
}
请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this