如何在不同的函数中使用变量?

我试图在下面的javascript中打印出latitude(lat)变量。

我如何引用lat变量? this.lat, that.lat, vicinity.lat等?

在我的JavaScript中我有

 var Vicinity = function (pubReference, sessionId, done, err) { this.ad = { getBannerHtml: function () { console.log(this.lat); // how do I refer to the lat variable? } }; this.init = function (done, err) { var that = this; this.getLatLng(that, function (position) { that.lat = position.coords.latitude; }, err); if (typeof done === 'function') done(this); }; this.init(done, err); }; $(document).ready(function () { var data = new Vicinity(pubReference, sessionId, function (result) { $("#sticky").html(result.ad.getBannerHtml()); } ); }); 

你快到了。 你已经在init()中声明that this 。 只需在整个function中执行此操作,它应该工作:

 var Vicinity = function (pubReference, sessionId, done, err) { var that = this; this.ad = { getBannerHtml: function () { console.log(that.lat); // how do I refer to the lat variable? } }; this.init = function (done, err) { var that = this; this.getLatLng(that, function (position) { that.lat = position.coords.latitude; }, err); if (typeof done === 'function') done(this); }; this.init(done, err); }; $(document).ready(function () { var data = new Vicinity(pubReference, sessionId, function (result) { $("#sticky").html(result.ad.getBannerHtml()); } ); }); 

您还可以使用“apply”function调用邻域范围内的getBannerHtml方法。 “this”变量设置为您传递的对象。

 $(document).ready(function () { var data = new Vicinity(pubReference, sessionId, function (result) { $("#sticky").html(result.ad.getBannerHtml.apply(result)); } ); }); 

我已经发布了另一篇文章,但又有了另一个想法;)这有点明显但有效。

 getBannerHtml: function(lat, lon) { return ''; } $(document).ready(function() { var pubReference = 1; var sessionId = "1"; var data = new Vicinity (pubReference, sessionId, function(result) { $("#sticky").html(result.ad.getBannerHtml(result.lat, result.lon)); } ); }); 

您还可以使用“apply”function调用邻域范围内的getBannerHtml方法。 “this”变量设置为您传递的对象。

 $(document).ready(function () { var pubReference = 1; var sessionId = "1"; var data = new Vicinity(pubReference, sessionId, function (result) { $("#sticky").html(result.ad.getBannerHtml.apply(result)); } ); });