Home>Article>Web Front-end> JavaScript: The role of this keyword and what you need to pay attention to when using it
Pure function call, which is the most common usage of functions, is a global call, so this represents the global object Global. Please take a look at the code below to see the results. Copy the code as follows
//一段正则,匹配所有_min.的图片src属性 var test = /^img[/]/; //遍历所有的图片节点 $("img").each(function(index, obj) { if (test.test($(this).attr("src"))) { var new_img; var this_img = $(this).attr("src"); $.ajax({ url : '/getImageUrl', type : 'post', data : { "getImageUrl" : this_img }, success : function(data) { console.log(data, "----data"); new_img = data; console.log(new_img, "----new_img"); $(this).attr("src", data); } }); console.log(new_img, "-----------------"); } })
This is to traverse the img tag src is the img object starting with "img/", take out the current src and request the server to obtain a new src to replace the original src ;
Note: $(this).attr("src", data); This statement does not take effect because this is no longer an img object, but an ajax object, so there is no To take effect, it should be replaced as follows:
//一段正则,匹配所有_min.的图片src属性 var test = /^img[/]/; //遍历所有的图片节点 $("img").each(function(index, obj) { if (test.test($(this).attr("src"))) { var new_img; var this_img = $(this).attr("src"); var this_src = $(this); $.ajax({ url : '/getImageUrl', type : 'post', data : { "getImageUrl" : this_img }, success : function(data) { console.log(data, "----data"); new_img = data; console.log(new_img, "----new_img"); this_src.attr("src", new_img); } }); console.log(new_img, "-----------------"); } })
As shown below, point the reference of the img object to a variable, and then use the variable to perform the replacement operation;
Question: The console.log(new_img, "-----------------"); at the end prints undefined for some reason, because this statement comes first for some reason. Execution, as shown below:
Related recommendations:
JavaScript scope and this keyword
Notes on using the volatile keyword in Java
Video tutorial:$this keyword in methods - the latest object-oriented OOP programming
The above is the detailed content of JavaScript: The role of this keyword and what you need to pay attention to when using it. For more information, please follow other related articles on the PHP Chinese website!