如何创建一个跟踪股票价格的 Javascript 对象?

How to create a Javascript object that keeps track of a stock price?

我想制作一个程序,可以跟踪多个股票对象并显示它们的基本信息(即:它们的价格)。

我有这个代码可以成功检索股票价格:

function getStock(symbol, callback){
          var url = 'https://query.yahooapis.com/v1/public/yql';
    var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

    $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
        .done(function (data) {
       result = data.query.results.quote.LastTradePriceOnly;
           callback(result);
        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log('Request failed: ' + err);
        });
}

getStock("goog", function(){alert(result)});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我希望能够创建一个可以跟踪股票的简单对象。但是,我在异步和 JSON 请求方面遇到了问题。这是我的 "stock" 对象的代码:

function getStock(symbol, callback) {
  var url = 'https://query.yahooapis.com/v1/public/yql';
  var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

  $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
    .done(function(data) {
      result = data.query.results.quote.LastTradePriceOnly;
      callback(result);
    })
    .fail(function(jqxhr, textStatus, error) {
      var err = textStatus + ", " + error;
      console.log('Request failed: ' + err);
    });
}

function stock(symbol) {

  this.price = 0;

  getStock(symbol, function(result) { //this function is my callback
    console.log(result);
    this.price = result;
  });

  this.printPrice = function() {
    alert("The price is: " + this.price);
  }
}


var s = new stock("goog");
$("#button").click(function() {
  s.printPrice()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Print Price</button>

您可能会注意到,我尝试使用回调,这似乎是解决此问题的合适方法(Javascript 的新功能)。但是,它似乎并没有真正设置 class 变量。在控制台中它确实打印了正确的价格,但它似乎没有改变 "this.price"(这是我需要它做的)

关于为什么这不起作用或如何创建 "updateStockPrice()" 方法的任何建议都非常有帮助。

你正在调用的这个

s.printPrice()

不再在同一范围内可以使用

alert("The price is: " + this.price);

因此添加对初始 this 的引用以进一步访问其在 class:

中的变量
var that = this;

function getStock(symbol, callback) {
  var url = 'https://query.yahooapis.com/v1/public/yql';
  var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

  $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
    .done(function(data) {
      result = data.query.results.quote.LastTradePriceOnly;
      callback(result);
    })
    .fail(function(jqxhr, textStatus, error) {
      var err = textStatus + ", " + error;
      console.log('Request failed: ' + err);
    });
}

function stock(symbol) {

  var that = this;
  
  that.price = 0;

  getStock(symbol, function(result) { //this function is my callback
    console.log(result);
    console.log("1");
    that.price = result;
  });

  that.printPrice = function() {
    alert("The price is: " + that.price);
  }
}


var s = new stock("goog");
$("#button").click(function() {
  s.printPrice()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Print Price</button>

我刚刚将 var price 更改为顶部,使其声明为函数的全局变量。这样,他们都可以共享它,您就可以打印它。

希望对您有所帮助!!

   function getStock(symbol, callback) {
  var url = 'https://query.yahooapis.com/v1/public/yql';
  var price=0;
  var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

  $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
    .done(function(data) {
      result = data.query.results.quote.LastTradePriceOnly;
      callback(result);
    })
    .fail(function(jqxhr, textStatus, error) {
      var err = textStatus + ", " + error;
      console.log('Request failed: ' + err);
    });
}

function stock(symbol) {


  getStock(symbol, function(result) { //this function is my callback
    console.log(result);
    price = result;
  });

  this.printPrice = function() {
    alert("The price is: " + price);
  }
}


var s = new stock("goog");
$("#button").click(function() {
  s.printPrice()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Print Price</button>

function getStock(symbol, callback) {
  var url = 'https://query.yahooapis.com/v1/public/yql';
  var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

  $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
    .done(function(data) {
      result = data.query.results.quote.LastTradePriceOnly;
      callback(result);
    })
    .fail(function(jqxhr, textStatus, error) {
      var err = textStatus + ", " + error;
      console.log('Request failed: ' + err);
    });
}

function stock(symbol) {

  this.price = 0;

  getStock(symbol, function(result) { //this function is my callback
    console.log(result);
    this.price = result;
  });

  this.printPrice = function() {
    alert("The price is: " + this.price);
  }
}


var s = new stock("goog");
$("#button").click(function() {
  s.printPrice()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Print Price</button>

是时候向 ES5bind 方法问好来设置执行上下文了。 Stock.getStock现在returns承诺-点击后将执行查询股票的最新价格。

function getStock(symbol, callback) {
    var url = 'https://query.yahooapis.com/v1/public/yql';
    var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

    $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
        .done(function (data) {
        result = data.query.results.quote.LastTradePriceOnly;
        callback(result);
    })
        .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log('Request failed: ' + err);
    });
}

function Stock(symbol) {
    this.price = 0;

    this.getStock = function () {
        var dfd = jQuery.Deferred();
        getStock(symbol, function (result) {
            this.price = result;
            dfd.resolve(result);
        }.bind(this));
        return dfd.promise();
    }.bind(this);

    this.printPrice = function () {
        alert("The price is: " + this.price);
    }.bind(this);
}

var s = new Stock("goog");
$("#button").click(function () {
    s.getStock().then(s.printPrice).done();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Print Price</button>

我为此制作了一个 jQuery 插件。希望这对某人有帮助

<!-- import jQuery and the plugin -->
<script src="bower_components/jquery/jquery.js"></script>
<script src="bower_components/jquery-stockquotes/dist/jquery.stockquotes.js"></script>
<link rel="stylesheet" type="text/css" href="bower_components/jquery-stockquotes/dist/jquery.stockquotes.css" />

<!-- the HTML integration -->
Twitter:  <span class="stock-quote" data-symbol="TWTR"></span>
Facebook: <span class="stock-quote" data-symbol="FB"></span>
Google:   <span class="stock-quote" data-symbol="GOOGL"></span>
Netflix:  <span class="stock-quote" data-symbol="NTFLX"></span>
Yahoo:    <span class="stock-quote" data-symbol="YHOO"></span>

<!-- the JS integration -->
<script>
$(document).on('ready', function () {
  $('.stock-quote').stockQuotes();
});
</script>

https://github.com/ajwhite/jquery-stockquotes