<!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>
通过函数调用模式看this指向
最新推荐文章于 2022-06-09 19:19:27 发布