JS中THIS的五种情况

事件绑定

/*
* THIS1:给元素的某个事件行为绑定方法,事件触发,方法执行,此时方法中的THIS一般都是当前元素本身
*/
//=>DOM0
 btn.onclick = function anonymous() {
 	console.log(this); //=>元素
 };
//=>DOM2
 btn.addEventListener('click', function anonymous() {
 	console.log(this);  //=>元素
 }, false);
 
 btn.attachEvent('onclick',function anonymous(){
 	// <= IE8浏览器中的DOM2事件绑定
 	console.log(this); //=>window
 });

 function fn() {	
 	console.log(this);
 }
 btn.onclick = fn.bind(window); //=>fn.bind(window)首先会返回一个匿名函数(AM),把AM绑定给事件;点击触发执行AM,AM中的THIS是元素,但是会在AM中执行FN,FN中的THIS是预先指定的WINDOW

函数执行(包括自执行函数)

/*
* THIS2:普通函数执行,它里面的THIS是谁,取决于方法执行前面是否有“点”,有的话,“点”前面是谁THIS就是谁,没有THIS指向WINDOW(严格模式下是UNDEFINED) 
*/
function fn() {
	console.log(this);
}
let obj = {
	name: 'OBJ',
	fn: fn
}; 
fn();
obj.fn();
console.log(obj.hasOwnProperty('name')); //=>hasOwnProperty方法中的this:obj  TRUE
console.log(obj.__proto__.hasOwnProperty('name')); //=>hasOwnProperty方法中的this:obj.__proto__(Object.prototype)  FALSE
console.log(Object.prototype.hasOwnProperty.call(obj, 'name')); //<=> obj.hasOwnProperty('name')

/*
* hasOwnProperty:用来检测某个属性名是否属于当前对象的私有属性  
* in是用来检测是否为其属性(不论私有还是公有) 
* 
* Object.prototype.hasOwnProperty=function hasOwnProperty(){}
*/
console.log(obj.hasOwnProperty('name')); //=>true
console.log(obj.hasOwnProperty('toString')); //=>false
console.log('toString' in obj); //=>true

new构造函数

/*
* THIS3:构造函数执行(new xxx),函数中的this是当前类的实例
*/
function Fn() {
	console.log(this);
	//=>this.xxx=xxx 是给当前实例设置私有属性
}
let f = new Fn; 

箭头函数

/*
* THIS4:箭头函数中没有自身的THIS,所用到的THIS都是其上下文中的THIS 
*   箭头函数没有的东西很多:
*      1.他没有prototype(也就是没有构造器),所以不能被new执行
*      2.他没有arguments实参集合(可以基于...args剩余运算符获取)
*/
let obj = {
	name: 'OBJ',
	fn: function () {
		// console.log(this); //=>obj
		let _this = this;
		return function () {
			// console.log(this); //=>window
			_this.name = "珠峰";
		};
	}
};
let ff = obj.fn();
ff(); 


let obj = {
	name: 'OBJ',
	fn: function () {
		// console.log(this); //=>obj
		return () => {
			console.log(this); //=>obj
		};
	}
};
let ff = obj.fn();
ff(); 


let obj = {
	name: 'OBJ',
	fn: function () {
		setTimeout(_ => {
			this.name = "珠峰";
		}, 1000);
	}
};
obj.fn(); 

call/apply/bind

/*
* THIS5:基于call/apply/bind可以改变函数中this的指向(强行改变)
*   CALL/APPLY
*     第一个参数就是改变的THIS指向,写谁就是谁(特殊:非严格模式下,传递null/undefined指向的也是window)
*     唯一区别:执行函数,传递的参数方式有区别,call是一个个的传递,apply是把需要传递的参数放到数组中整体传递
*     func.call([context],10,20) 
*     func.apply([context],[10,20])
*   BIND
*     call/apply都是改变this的同时直接把函数执行了,而bind不是立即执行函数,属于预先改变this和传递一些内容  =>"柯理化"
*/
/* Function.prototype={
	call
	apply
	bind
}; */

// ~ function anonymous(proto) {
// 	/* function bind(context) {
// 		//context may be null or undefined
// 		if (context == undefined) {
// 			context = window;
// 		}
// 		//获取传递的实参集合
// 		var args = [].slice.call(arguments, 1);
// 		//需要最终执行的函数
// 		var _this = this;
// 		return function anonymous() {
// 			var amArg = [].slice.call(arguments, 0);
// 			_this.apply(context, args.concat(amArg));
// 		};
// 	} */

// 	//经过测试:apply的性能不如call
// 	function bind(context = window, ...args) {
// 		return (...amArg) => this.call(context, ...args.concat(amArg));
// 	}

// 	/* function call(context = window, ...args) {
// 		//=>必须保证context是引用类型
// 		context.$fn = this;
// 		let result = context.$fn(...args);
// 		delete context.$fn;
// 		return result;
// 	} */

// 	function call(context = window, ...args) {
// 		context === null ? context = window : null;
// 		let type = typeof context;
// 		if (type !== "object" && type !== "function" && type !== "symbol") {
// 			//=>基本类型值
// 			switch (type) {
// 				case 'number':
// 					context = new Number(context);
// 					break;
// 				case 'string':
// 					context = new String(context);
// 					break;
// 				case 'boolean':
// 					context = new Boolean(context);
// 					break;
// 			}
// 		}
// 		context.$fn = this;
// 		let result = context.$fn(...args);
// 		delete context.$fn;
// 		return result;
// 	}

// 	function apply(context = window, args) {
// 		context.$fn = this;
// 		let result = context.$fn(...args);
// 		delete context.$fn;
// 		return result;
// 	}

// 	proto.bind = bind;
// 	proto.call = call;
// 	proto.apply = apply;
// }(Function.prototype);

// let obj = {
// 	fn(x, y) {
// 		console.log(this, x, y);
// 	}
// };
// obj.fn.call({}, 10, 20);
// obj.fn.apply(window, [10, 20]);

// setTimeout(obj.fn.bind(window, 10, 20), 1000);
// setTimeout(anonymous, 1000);  1S后先执行bind的返回结果anonymous,在anonymous中再把需要执行的obj.fn执行,把之前存储的context/args传给函数
// document.body.onclick = obj.fn.bind(window, 10, 20);
// document.body.onclick = anonymous;
	/* 
	function call(context = window, ...args) {
			context.$fn = this;
			let result = context.$fn(...args);
			delete context.$fn;
			return result;
		} => AAAFFF000*/

		function fn1() {
			console.log(1);
		}

		function fn2() {
			console.log(2);
		}
		fn1.call(fn2); //=>执行的是FN1 =>1
		/*
		 * call执行
		 *   this=>fn1
		 *   context=>fn2
		 *   args=>[]
		 * fn2.$fn = fn1;  fn2.$fn(...[])
		 */
		fn1.call.call(fn2); //=>执行的是Fn2 =>2
		/*
		 * 先让最后一个CALL执行
		 *   this=>fn1.call=>AAAFFF000
		 *   context=>fn2
		 *   args=>[]
		 * fn2.$fn=AAAFFF000  fn2.$fn(...[])
		 *
		 * 让CALL方法再执行
		 *    this=>fn2
		 *    context=>undefined
		 *    args=>[]
		 * undefined.$fn=fn2  undefined.$fn()
		 * 
		 * 让fn2执行
		 */
		Function.prototype.call(fn1);
		/*
		 * 先让最后一个CALL执行
		 *     this=>Function.prototype(anonymous函数)
		 *     context=>fn1
		 *     args=>[]
		 * fn1.$fn=Function.prototype   fn1.$fn()
		 * 让Function.prototype执行
		 */
		Function.prototype.call.call(fn1); //=>1
		/*
		 * 先让最后一个CALL执行
		 *     this=>Function.prototype.call(AAAFFF000)
		 *     context=>fn1
		 *     args=>[]
		 * fn1.$fn=AAAFFF000   fn1.$fn()
		 * 
		 * 让CALL执行
		 *    this=>fn1
		 *    context=>undefined
		 *    args=>[]
		 * undefined.$fn=fn1   undefined.$fn()
		 * 让fn1执行
		 */
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值