this

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>this</title>
	</head>
	<body>
		<script>
			/*
			 
			 * 1.this是指当前方法或者属性所在的对象
			 * 2.注意:1)避免在函数中多层使用this
			 * 			2)避免数组调用使用this
			 * 			3)避免回调函数中使用this
			 * 
			 * */
			var person={
				role:'parent',
				child:{
					son:function(){
						console.log(this);  //this指向person.child
					}
				}
			};
			person.child.son();
			
			var o={
				f1:function(){
					console.log(this);     //指向o
					var f2=function(){
						console.log(this);    //指向window
					}();
				}
			};
			o.f1();
			//修改
			var o={
				f1:function(){
					console.log(this); 
					var that=this;
					var f2=function(){
						console.log(that);    
					}();
				}
			};
			o.f1();
				
			var counter = {
				count: 0,
				inc:function () {
	//				'use strict';			//在严格模式下this指向顶层环境,会报错
					this.count++;
					console.log(this);
				}
			};
			var f = counter.inc;   //相当于把counter.inc放在全局环境中,然后再执行   this指向window
			f();
			counter.inc();			//直接执行counter.inc()方法			this指向counter对象
			
			var arr_obj={
				v:'hello',
				p:['a','b'],
				f:function(){
					var that=this;
					this.p.forEach(function(item){
						console.log(that.v+' '+item);
					});
				}
			};
			arr_obj.f();
			//找出数组中的最大值
			var arr=[1,2,3,5,9,3];
			console.log(Math.max.apply(this,arr));
			//将类似数组的对象转化成数组
			console.log(Array.prototype.slice.apply({0:5,length:1}));
			//利用call调用对象的原生方法
			var obj_pro={}
			console.log(obj_pro.hasOwnProperty('toString'));
			obj_pro.toString=function(){
				return true;
			};
			console.log(obj_pro.hasOwnProperty('toString'));
			//Object的原生方法已经被改变
			console.log(Object.prototype.hasOwnProperty('toString'));
			//解决:使得在obj_pro作用域中运行hasOwnProperty()方法
			Object.prototype.hasOwnProperty().call(obj_pro,'toString');
		</script>
	</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值