如何在不同的函数中使用变量? [英] How to use a variable in a different function?
本文介绍了如何在不同的函数中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在下面的javascript中打印出latitude(lat)变量。
Im trying to print out the latitude (lat) variable in the javascript below.
如何引用lat变量? this.lat,that.lat,nearby.lat
等?
How do I refer to the lat variable? this.lat, that.lat, vicinity.lat
etc ?
在我的javascript中我有
In my javascript I have
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());
}
);
});
推荐答案
我已经在另一篇文章中发帖但得到了另一个想法; )
有点明显但有效。
I already posted in another post but got another idea ;) It is kind of obvious but works.
getBannerHtml: function(lat, lon) {
return '<iframe src="http://foo.com?pr=34&lat'+ lat +'=&lon=' + lon + '"></iframe>';
}
$(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功能调用邻域范围内的getBannerHtml方法。 this变量设置为您传递的对象。
You can also call the getBannerHtml method in the scope of your Vicinity by using the "apply" function. The "this" variable is set to the object you pass.
$(document).ready(function () {
var pubReference = 1;
var sessionId = "1";
var data = new Vicinity(pubReference, sessionId,
function (result) {
$("#sticky").html(result.ad.getBannerHtml.apply(result));
}
);
});
这篇关于如何在不同的函数中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文