好的,我知道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(又名"上下文")是每个函数内部的特殊关键字 它的值只取决于函数的调用方式,而不是 如何/何时/何地定义。它不受词法范围的影响, 像其他变量一样。
答案 0 :(得分:1)
当你调用一个对象的方法时,它只有在你把它作为对象的一个成员调用时才有效,如果你得到对该函数的引用或者把它称为常规函数,那么上下文就不是对象。它只是你如何调用决定上下文的函数,上下文不是继承的,所以如果你从一个方法调用一个函数它只是一个常规的函数调用。
示例:
function Dog() {
function bark() {}
this.bark = bark;
this.barkThrice() {
bark(); // function call; context = window
this.bark(); // method call; context = the object
var b = this.bark;
b(); // function call; context = window
}
}
要将该函数作为对象的方法调用,您需要使用call
method(或bind
或apply
)来设置调用的上下文:
function Cat() {
this.theCatName = "Mistigri";
function meow() { alert(this.theCatName + " meow"); }
this.meow = function() { meow.call(this); };
}
var MyCat = new Cat();
MyCat.meow();
答案 1 :(得分:0)
我希望这会有所帮助: 函数内声明的变量在该函数之外是不可访问的。 函数中定义的变量可以被其嵌套函数访问。
function Cat() {
// public var exist on the Cat instance: accesible from outside the Cat constructor
this.theCatName = "Mistigri";
// public function exist on the Cat instance
// has access to all variables defined in the Cat constructor (_theCateName and _meow)
// and all variables and methods defined on 'this'
// this reference to a Cat Instance
this.meow = function() {
alert(this.theCatName);
_meow();
}
// private var only accessible within the Cat constructor.
var _theCateName = "_Mistigri"
// private function only accessible within the Cat constructor.
function _meow() {
// _meow is defined as closure in the Cat constructor
// In the function _meow 'this' is a reference to the scope from where the Cat function / constructor was applied (the window object in this case)
alert(this.theCatName + " meow " + _theCateName); // outputs: undefined meow _Mistigri
};
}
var MyCat = new Cat()
MyCat.meow()
alert (MyCat.theCatName)// outouts: Mistigri