在Javascript中,this这个关键字能够说是用的很是多,说他简单呢也很简单,说他难呢也很难,有的人开发两三年了,本身好像也说不清this究竟是什么。下面咱们来看看:javascript
一、在通常函数方法中使用 this 指代全局对象java
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 出的对象app
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运行一下本身就知道了。this
以上部份内容来自网络,有问题能够在下面评论,技术问题能够在私聊我。code
技术QQ群:213365178对象