gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:08:04 24 4
gpt4 key购买 nike

我正在尝试在下面的 JavaScript 中打印出纬度 (lat) 变量。

如何引用 lat 变量? this.lat、that.lat、neighborhood.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。只要在整个函数中这样做,它就应该起作用:

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());
}
);
});

关于javascript - 如何在不同的函数中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com