Javascript 如何在不同的函数中使用变量?
我试图在下面的javascript中打印出纬度(lat)变量 如何引用lat变量Javascript 如何在不同的函数中使用变量?,javascript,jquery,Javascript,Jquery,我试图在下面的javascript中打印出纬度(lat)变量 如何引用lat变量this.lat,that.lat,neighborary.lat等等 在我的javascript中,我有 var Vicinity = function (pubReference, sessionId, done, err) { this.ad = { getBannerHtml: function () { console.log(this.lat); // ho
this.lat,that.lat,neighborary.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()
中将声明为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());
}
);
});
您还可以使用“apply”函数在附近的范围内调用getBannerHtml方法。“this”变量设置为传递的对象
$(document).ready(function () {
var data = new Vicinity(pubReference, sessionId,
function (result) {
$("#sticky").html(result.ad.getBannerHtml.apply(result));
}
);
});
$(document).ready(function () {
var pubReference = 1;
var sessionId = "1";
var data = new Vicinity(pubReference, sessionId,
function (result) {
$("#sticky").html(result.ad.getBannerHtml.apply(result));
}
);
});
我已经在另一个帖子上发布了,但有了另一个想法;)
这有点明显,但有效
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));
}
);
});
如果您不“拥有”iFrame,即它与父页面位于同一个域中,则无法从其中访问变量。如果您认为this
在getBannerHtml
中引用approach
或由approach
创建的实例,则是指this.ad
对象。因此,如果将其缓存到变量that
中会更好。请看函数getBannerHtml:function()中如何引用lat和lon变量?this.lat,that.lat,neighboration.ad.lat?在本例中为console.log(this.lat)代码>这是邻近。ad
挑剔:在此代码中,lat
是一个属性,而不是一个变量。仅供参考:已从