this != JavaScript 中的 this (好吧,有时......)
示例 1
var Reptile = function () {
var reptile = this;
this.showBla = function() {
alert(reptile.bla);
}
}
var turtle = new Reptile();
turtle.bla = 'whatever';
turtle.showBla();
示例 2
var Reptile = function () {
this.showBla = function() {
alert(this.bla);
}
}
var turtle = new Reptile();
turtle.bla = 'whatever';
turtle.showBla();
示例 1 合法吗?因为有时直接在构造函数中定义“this”似乎把事情搞砸了......?!?
Example 1
var Reptile = function () {
var reptile = this;
this.showBla = function() {
alert(reptile.bla);
}
}
var turtle = new Reptile();
turtle.bla = 'whatever';
turtle.showBla();
Example 2
var Reptile = function () {
this.showBla = function() {
alert(this.bla);
}
}
var turtle = new Reptile();
turtle.bla = 'whatever';
turtle.showBla();
Is example 1 legit? As it sometimes seems to screw things over to define "this" directly in the constructor...?!?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,它是合法的,并且在您可能需要在函数内定义一个函数并且可以以“this”将指向其他内容的方式调用的情况下很有用。书籍建议将此变量命名为 var that = this;
Yes, it is legit and is useful in cases where you may need to define a function inside a function that may be invoked in a way there "this" will pointer to something else. Books recommend naming this variable var that = this;
示例 1 是维护对当前实例的引用的常见模式。在回调情况下,例如:
示例 1 的
var reptile...
保存this
引用并显示'whatever'
。示例 2 将显示undefined
,除非您在调用方手动分配范围(例如,在 jQuery 中):Example 1 is a common pattern for maintaining the reference to the current instance. In a callback situation, like:
Example 1's
var reptile...
saves thethis
reference and will show'whatever'
. Example 2 will showundefined
, unless you manually assign scope on the calling side (e.g., in jQuery):