![](/img/trans.png)
[英]Add function to constructor prototype with method with access to this from constructor instance
[英]How to access a method/field of a constructor from a nested function
我正在嘗試從嵌套函數訪問構造函數的字段。
這是我的代碼:
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?
}
}
}
如果我這樣調用scroll方法:
var a = new Box();
$("#button").click(function() {
a.guide.scroll();
});
Box.div
返回未定義狀態。
如果我嘗試將scroll
方法中的div屬性的id
alert
為this.div
,它將使用guide
對象中的div屬性。 我嘗試使用Box.div
引用參考guide
對象之外的div字段,但這不起作用。 請幫我解決這個問題。
將此添加到Box函數的第一行:
var Box = function() {
var self = this;
則警示,用self
來代替this
因為this
是不是指的頂級功能(盒)。
$(document).scrollTo(self.div);
這是因為滾動功能中的“ this”對象是指功能本身。 您需要緩存對最外面的“ this”對象的引用,並使用它代替。 有關示例,請參見此小提琴:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.