【JavaScript】一文搞懂JS中this指向
一、this是什么
在函数执行时,每次JS都会在函数内部传入一个隐含的参数 this,this指代当前的运行环境。
二、this作用
改变函数中的this指向,并将函数返回。
三、JS中的八种指向
this的指向是一个对象,根据函数调用方式的不同,this的值也不同,一般指向调用者。
1、全局作用域内,this指向window
//1、 console.log(this === window);//true //2、 var name="张三"; console.log(this.name); //张三 console.log(window.name); //张三
2 、普通函数形式调用,this指向window
function fn(){ console.log(this); } fn();//window var name = 张三; // 创建一个函数,来打印name属性 function fn(){ console.log(this.name); } fn();//张三
3、对象方法形式调用,this指向该方法所属对象
function fn(a,b){ alert(this); alert(a=+a+,b=+b); } obj.fn(); //a = undefined b = undefined
4、构造函数(原型方法)形式调用 ,this指向实例对象
var name = "小明"; function testThis(){ this.name = 小红; this.sayName = function () { return this.name; } } console.log(this.name ); // 小明 new testThis(); // 没赋值 console.log(this.name); // 小明 var result = new testThis(); console.log(result.name ); // 小红 console.log(result.sayName()); // 小红 testThis(); console.log(this.name ); // 小红 //只要被new了就指向谁
5、定时器、匿名函数调用,this指向window
setTimeout(function(){ console.log(定时器里的this+this); },1000) //window
(function(){ console.log(立即执行函数this+this); })(); //window
6 、箭头函数this指向包裹箭头函数的第一个普通函数
沿着作用域找
let name = "小明"; let o = { name : "小红", sayName: function () { console.log(this.name) }, func: function () { setTimeout( () => { this.sayName(); },100); } }; o.func() //小红
7、事件方法调用,this指向事件源
var btn = document.getElement.querySelector(button); btn.onclick=function(){ console.log(绑定事件函数的this+this); // [object HTMLButtonElement]
8、call和apply、bind
属于大写 Function原型上的方法,只要是函数就会可以使用。 (1)两个参数:指定函数中this、参数映射到对应的函数。 (2)call的实参是一个一个传递,apply的实参需要封装到一个数组中传递。 (3)bind 在调用的时候,需要变量接收,接收后在调用。
function f1(a, b) { console.log(this) console.log(a + ==== + b) } var obj = { name: 小明, age:15, eat(){ console.log("我爱吃"); } } // 1、call---->传递的参数,是一个一个的传入进去的 // 指定this 传参 映射到对应的函数 f1.call(null, 10, 20); // window 10====20 f1.call(obj, 100, 200); // {name: "小明", age: 15, eat: ƒ} 100====200 // 2、apply--->传递的参数,是以数组的形式传入进去的 f1.apply(null, [30, 40]) //window 30====40 f1.apply(obj,[300,400]) //{name: "小明", age: 15, eat: ƒ} 300===400 // 3、bind方法 需要变量接收 再次才能调用执行 var ff = f1.bind(null) // window ff(1000,2000) // 1000====2000 var ff = f1.bind(obj) // {name: "小明", age: 15, eat: ƒ} ff(10, 20) //10====20
上一篇:
IDEA上Java项目控制台中文乱码