JS中的this是什么,this的四种用法

在Javascript中,this这个关键字可以说是用的非常多,说他简单呢也很简单,说他难呢也很难,有的人开发两三年了,自己好像也说不清this到底是什么。下面我们来看看:

1、在一般函数方法中使用 this 指代全局对象

function hello(){
   this.x = 1;
   console.log(this.x)
}

hello();
//此时控制台打印1

2.作为对象方法调用,this 指代上级对象

function hello(){
   console.log(this.x)
}

var s = {};
s.x = 1;
o.m = hello;
o.m();
//此时控制台打印1

3.作为构造函数调用,this 指代new 出的对象

function hello(){
   this.x = 1;
}

var s = new hello();
console.log(s.x)
//运行结果为1,为了表明这是this不是全局对象,我们对代码做一些改变

var x = 2;
function hello(){
   this.x = 1;
}

var o = new hello();
console.log(x)

4.apply 调用 ,apply方法作用是改变函数的调用对象,此方法的第一个参数为改变后调用这个函数的对象,this指代第一个参数

var x = 0;
function hello(){
   console.log(this.x)
}

var h = {};
h.x = 1;
h.m = hello;
h.m.apply();  //输出为0

h.m.apply(h) //输出1

以上就是常用的四种方法,大家要是不明白,可以把demo运行一下自己就知道了。

以上部分内容来自网络,有问题可以在下面评论,技术问题可以在私聊我。

技术QQ群:213365178

原文地址:https://www.cnblogs.com/c1024/p/11012012.html