通过函数调用模式看this指向

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
<ul>
	<li>1</li>
	<li></li>
	<li></li>
	<li></li>
	<li></li>
	<li></li>
	<li></li>
</ul>
<script>

	var global = 10; 
	//1.函数模式(前面不能有通过 XXX 得到 函数名 的行为)
	//特点:独立运行,调用语法格式前没有任何引导数据
	function fun1(){
		console.log(this,"函数模式") //this---->window
		this.global = 5
		console.log(this.global)
		return this.age;
	}
	fun1();


	//2.构造器模式
	//需要知道构造器的执行过程
	//语法:通过new  构造函数
	
	function persion(){
		this.name = 10
		this.age = 20
		this.man = function(){
			return `我的名字是${this.name},今年${this.age}`
		}
		this.oth = fun1;
	}
	persion.prototype.eats = function(){
		return "meat"
	}
	var p = new persion();


	console.log(p)
	console.log(p.eats())
	// 先使用 new 运算符(分配内存空间),在JS中创建空的,具有原型结构的对象
	//  具有原型结构,该对象的原型(__prop__)是persion.prototype
	//  调用构造函数
	//  创建上下文
	//  ---
	//  ...
	


	//3.方法调用模式
	//一个函数对位对象的一个成员,由对象引导调用。这个方法就是方法调用
	//表现:调用前有一个引导数据:满足通过XXX访问到的方法名
	
	var obj = {
		sayHello:function(){console.log(this,"方法调用模式")}
	}
	obj.sayHello()



	//4.上下文调用模式(动态绑定)
	//语法:函数名.call(上下文,参数1,参数2,...) 任意参数
	//函数名.apply(上下文,[参数1,参数2,...]) 最多两个参数

	function context(){
		if(this.name != undefined ){console.log(this.name,"调用")}
			console.log(this,)
	}
	context()
	//call apply方法的第一个参数就是决定上下文的东西
	//你传入什么  上下文就是什么(this就是什么)
	//如果传入的是 引用类型 除了null外 就是表示的this
	//如果传入的是基本类型(数字,布尔...),则转换成包装类型
	//如果传入的是空 (null,undefined)那么上下文则为window
	//ps:call/apply  第一个参数即为指定this 后面则为函数正常所需参数
	context.apply({"name":"张三"})
	context.apply(123)
	//demo1
		let dom1 = document.getElementsByTagName("li")
		//console.log(dom1.slice(0,5))  -->报错
		let truethArr = Array.prototype.slice.call(dom1,0,5)
		console.log(truethArr)


	//5.bind模式
	//bind已开启就已经绑定,在之后的使用中就不需要再绑定,每次使用时都是一开始绑定的哪一个this
	//语法:函数.bind(对象) 返回已绑定this的新函数
	//demo 2
	 let $ = document.querySelectorAll.bind(document)
	 console.log($("li"))

	//补充:箭头函数不改变this
</script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值