js call() apply() bind() -改变this指向


参考下例找区别:

/* 
	 * call() apply() bind()
	 * 
	 * call() apply() 运行时绑定this对象为“abc”
	 * bind() 定义时绑定this对象为“abc”  
	 * 
	 */
	function show(a,b) {
		 alert(`
                this:${this}\n
                a:${a}\n
                b:${b}
            `)
	}
	
	
	//show.call("abc",12,5);//执行结果: abc 12 5
	
	//show.apply("abc",[12,5]);//执行结果: abc 12 5
	
	var cc = show.bind("abc");// 只是绑定,并没执行方法
	cc(12,5);//执行方法  执行结果: abc 12 5


三者区别:

call(this指向谁,arg1,arg2,...)  // 参数一个一个传

apply(this指向谁,[arg1,arg2...])  // 参数为数组

bind(this指向谁)   // 定义时不传参,调用时再传参


而bind()比较常用如:

	var a=2;
	var json = {
		a:1,
		show(){
			//alert(this.a);// 输出:1
			setTimeout(function(){
				alert(this.a);// setTimeout中this默认为window,使用bind()改变this为json对象
			}.bind(this),1000)
		}
	}
	json.show();// 正确输出:1,而不是:2



你可能感兴趣的:(javascript)