我今天已经阅读了数十篇关于JavaScript的闭包和作用域的文章和帖子,但仍然不明白为什么我无法从CoreClass中访问Socket以及到达那里的方式:
CoreClass = function() {
console.log('CoreClassLocalisation', Localisation) // works??
console.log('CoreClassSocket', Socket) // undefined, hell why, its even closer?
}
var Localisation = 'im a localisation'
Request = function() {
var Socket = 'im a socket'
new CoreClass()
}
new Request
答案 0 :(得分:0)
它仅存在于Request
范围内,因为您在该函数中定义了它(var Socket
)。
相反,您在外部作用域中定义Localisation
,可以由CoreClass
的内部作用域访问。
可能的解决方法:
CoreClass = function() {
console.log('CoreClassLocalisation', Localisation) // works??
console.log('CoreClassSocket', Socket) // undefined, hell why, its even closer?
}
var Localisation = 'im a localisation'
var Socket
Request = function() {
Socket = 'im a socket'
new CoreClass()
}
new Request
另一个:
CoreClass = function(Socket) {
console.log('CoreClassLocalisation', Localisation) // works??
console.log('CoreClassSocket', Socket) // undefined, hell why, its even closer?
}
var Localisation = 'im a localisation'
Request = function() {
var Socket = 'im a socket'
new CoreClass(Socket)
}
new Request
甚至其他解决方法