簡體   English   中英

如何在不更改功能結構的情況下保留上下文?

[英]How do I keep the context without changing the structure of function?

如何保持上下文並從ajax響應中獲取真實數據,並堅持我代碼的當前結構?

例如:在第二種情況下,我得到了正確的數據。 使用當前結構如何獲得相同的結果? (第一個console.log)

 var options = { url: 'http://echo.jsontest.com/key/value' }; function getJson(options) { this.init(options); } $.extend(getJson.prototype, { options: null, init: function (options) { this.options = options; return $.get(this.options.url); } }); console.log('First:'); console.log(new getJson(options.url)); console.log('Second:'); console.log($.get(options.url)); 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 

這是使用代碼的方法。 您只需將options傳遞給getJson ,而無需傳遞options.url

您的init函數會返回一個promise,因此您可以使用.then.done處理結果。

 var options = { url: 'https://jsonplaceholder.typicode.com/todos/1' }; function getJson(options) { return this.init(options); } $.extend(getJson.prototype, { options: null, init: function (options) { this.options = options; return $.get(this.options.url); } }); $.when( new getJson(options) ) .then(function(data) { console.log(data); }) .fail(function(data, statusText) { console.log(statusText) }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM