javascript改变this指向的三种方法

apply和call都是为了改变某个函数运行时的上下文而存在的(就是为了改变函数内部this的指向);

如果使用apply或call方法,那么this指向他们的第一个参数,apply的第二个参数是一个参数数组call的第二个及其以后的参数都是数组里面的元素,就是说要全部列举出来。

         <script type="text/javascript">

			var number = [56,36,-18];
			var maxInNumber = Math.max.apply(Math,number);
			var maxnumber = Math.max(12,26);
			console.log(maxnumber);//26
			console.log(maxInNumber);//56
			/**
			 * apply第一个参数传入的是一个对象(当前函数的this是指向这个对象的,如果或者实例化后的函数),第二个是传入的是一个数组
			 * call第一个参数传入的也是一个对象,后面的参数是一个一个的数组里面的元素,这里如果传入null或者undefined,this就会绑定给顶层对象
			 * bind第一个参数传入的也是一个对象,只不过bind绑定后得到的是一个未运行的方法,而call或者apply都是会立即执行的
              *如果多次调用bind,那么多出来的次数都是无效的,
               */ function cat(bgg,melon){ this.bgg = 123; this.melon = "456"; console.log(123); } var catdemo = new cat("123"); function mouse(){ var name = "123"; document.write("1223"); } var test = mouse.bind(catdemo); test();//页面输出1123 console.log(test);//打印出返回后的函数mouse,包括注释。 </script>

  

posted @ 2017-03-27 01:53  熊猫哥哥  阅读(580)  评论(0编辑  收藏  举报