如何从嵌套函数访问构造函数的方法/字段

How to access a method/field of a constructor from a nested function

本文关键字:方法 字段 构造函数 访问 嵌套 函数      更新时间:2023-09-26

我正试图从嵌套函数访问构造函数的字段。

这是我的代码:

var Box = function() {
  this.div = $("div#mydiv");
  this.guide = {
     div: $("div#mydiv2"),
     scroll: function() {
        $(document).scrollTo(this.div); //Want to scroll to mydiv2
        alert(Box.div.attr("id")); //Want to alert mydiv id
                                   //How do I access the div field of the Box constructor?
     }
  }
}

如果我这样调用滚动方法:

var a = new Box();
$("#button").click(function() {
a.guide.scroll();
});

Box.div返回为未定义。

如果我尝试将scroll方法中div属性的id alert作为this.div,它将使用guide对象中的div属性。我尝试过使用Box.divguide对象外部引用div字段,但这不起作用。请帮我弄清楚。

将其添加到Box函数的第一行:

var Box = function() {
    var self = this;

然后在警报中,使用self而不是this,因为this不是指顶级功能(框)。

$(document).scrollTo(self.div); 

这是因为滚动函数中的"this"对象指的是函数本身。您需要缓存对最外层"this"对象的引用,然后使用它。见这个小提琴的例子:

http://jsfiddle.net/tuando/kBc5K/