PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

JavaScript : this关键字的作用及使用时需要注意的地方

php是最好的语言
php是最好的语言 原创
2018-07-26 10:08:31 1143浏览

纯粹的函数调用 ,这是函数的最通常用法,属于全局性调用,因此this就代表全局对象Global。 请看下面这段代码,运行结果如何。 复制代码代码如下

//一段正则,匹配所有_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, "-----------------");

		}
	})


这是 遍历img标签src是以 "img/" 开头的 img对象,取出当前src请求服务器获取新的src替换原来的src;

注意 : $(this).attr("src", data); 这个语句没有生效是因为this已不是img对象,而是ajax对象所以没有生效,应替换如下:

//一段正则,匹配所有_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, "-----------------");

		}
	})

如下图,把img对象的引用指向一个变量,然后用该变量执行替换操作;

20180725162544730.png

疑问 : 尾部的console.log(new_img, "-----------------"); 不知为何打印的是undefined ,因为 这个语句不知为何会最先执行,如下图:

20180725163016660.png

相关推荐:

JavaScript scope作用域与this关键字

Java使用volatile关键字的注意事项

视频教程:方法中的$this关键字-最新的面向对象OOP编程

以上就是JavaScript : this关键字的作用及使用时需要注意的地方的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。