改变函数内部this指向

52 阅读1分钟

js处理函数内部指向

call方法

1、调用函数 2、改变this指向

		var o = {
			name:'andy'
		}

		function fn(){
			console.log(this);
		}
		fn();  //此时this指向windows
		fn.call(o)  //this指向 o

3、实现继承

		function Father(name, age) {
			this.name = name;
			this.age = age
		}

		function Son(name, age) {
			Father.call(this,name,age)
		}
		var son = new Son('张三',18)
		console.log(son);  //Son {name: '张三', age: 18}
                
                
apply方法

1、调用函数 2、改变this指向 3、参数必须是数组

		var o = {
			name:'andy'
		}

		function fn(arr){
			console.log(this);
			console.log(arr);
		}
		fn();//此时this指向windows
		fn.apply(o,['数组'])//this指向 o
bind方法

1、不会调用函数 2、改变this指向 3、参数必须是数组 4、返回的是原函数改变this之后的新函数

		var o = {
			name:'andy'
		}

		function fn(a,b){
			console.log(this);
			console.log(a+b);
		}
		var f = fn.bind(o,1,2)
		f()