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

时间:2014-07-06 09:54:52

标签: javascript jquery

我试图在下面的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());
        }
    );
});

3 个答案:

答案 0 :(得分:0)

你快到了。您已在that中声明thisinit()。只需在整个功能中执行此操作即可:

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

答案 1 :(得分:0)

您还可以使用" apply"来调用邻域范围内的getBannerHtml方法。功能。 "这"变量设置为您传递的对象。

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

答案 2 :(得分:0)

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

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

您还可以使用&#34; apply&#34;来调用邻域范围内的getBannerHtml方法。功能。 &#34;这&#34;变量设置为您传递的对象。

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