javascript:使用call或者apply扩充作用域

版权声明:分享才能获得最大的价值 https://blog.csdn.net/qq_32252957/article/details/87890658

apply() 和 call()这两个方法,我们不止是用来做参数传递的,我们可以改变this,也就是让方法本身和方法中使用的this对象无耦合。


eg1:

	<script>
		this.name = "name inwindow";
 
		function methods1() {
			console.log("下方打印的是作用于下的name属性")
			console.log(this.name);
		}
 
		function methods2() {
			let mycontext = {
				"name": "name in mycontext"
			};
			methods1.call(mycontext);
		}
		methods2(); //name in mycontext,methods1()函数中this是指mycontext
		//也就是说methods()与this.name也就是window.name和mycontext对象没有耦合关系,这样也就带来了灵活性
		methods1(); //name inwindow
	</script>

eg2:

window.color="red";
var o ={color:"blue"};
function sayColor(a,b){alert(this.color);}
sayColor();//red
sayColor.call(this,1,2);//red
sayColor.call(window,1,2);//red
sayColor.call(o,1,2);//blue  

在使用call()方法时,必须明确地传入每一个参数。结果和apply一样。
其实apply和call真正的强大用途在于,能够扩充函数赖以运作的作用域:
这样扩充的最大好处,就是对象不需要与方法有任何耦合关系。


相信大家已经理解了,看了三四篇博客才理解最后一句话,这里分享给大家,加油!

猜你喜欢

转载自blog.csdn.net/qq_32252957/article/details/87890658