【发布时间】:2024-04-16 09:55:02
【问题描述】:
好的,我知道在 JavaScript 中关于this 的范围有几千个奇怪的线程(这让人怀疑该语言是否设计得很好)——但我仍然无法解释“这个”:
//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = meow }
}
var MyCat = new Cat()
MyCat.meow()
//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = function() { alert(this.theCatName + " meow") }
}
var MyCat = new Cat()
MyCat.meow()
//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
Cat.prototype.meow = function() { alert(this.theCatName + " meow") }
}
var MyCat = new Cat()
MyCat.meow()
//doesn't work
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = function() { meow() } }
}
var MyCat = new Cat()
MyCat.meow()
//doesn't work
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
Cat.prototype.meow = function() { meow() } }
}
var MyCat = new Cat()
MyCat.meow()
现在我的理解是,在后两种情况下,Cat.prototype.meow 或 this.meow 是匿名函数,恰好调用 meow(),这是 Cat() 的内部函数 - 但 this 的上下文很清楚指函数内部的 cat - 它会发生什么?
这是一个半规范的答案: See How to access the correct this / context inside a callback? 但它只有以下内容来说明“this”的实际上下文是什么:
this(又名“上下文”)是每个函数中的一个特殊关键字,并且 它的值仅取决于函数的调用方式,而不取决于 如何/何时/何地定义它。它不受词法作用域的影响, 像其他变量一样。
【问题讨论】:
标签: javascript scope