this
指向当前对象。
各种情况:
全局上下文
node.js对全局上下文this特殊处理。
console.log(this); ——输出 {}
this 全局上下文和函数指向 全局
函数
var func=function(){ console.log(this); } func(); // 全局
对象
- 只有对象.方法,this指向当前对象;其余都是指向全局。
- 在对象的方法使用this,指向当前对象
-
在对象方法里嵌套,普通函数的调用,指向全局
var stu=(){ name:'ww', intro:function(){ console.log(this,this.name); } } stu.intro();
改变this的指向方法
call , apply
执行函数,并改变this指向
区别:
- call:以参数列表形式传递;
-
apply:以数组传递
var func=function(a,b){ console.log(this); console.log('hello',a,b); } func.call(11,22); func.call('hello',[11,22]);
bind
声明函数,在函数后面{}末尾。
函数声明时,利用 bind 改变this指向。
箭头函数 =>
箭头函数中的this和上下文的this一致。
内部没有作用范围(上下文),this指向和外部一样。
var func1 = a => (++a); ()表示有return.
7、 var myObject={ foo:'bar', func:function(){ var self=this; console.log(this.foo); // bar; console.log(self.foo); // bar; self=this (function(){ // 嵌套,指向全局 console.log(this.foo); // undefined; 未定义,在整个(var myObject)外部找,没有foo console.log(self.foo); // bar; 找的上一个console.log(self.foo);输出的值 })() } } myObject.func();
8、 var User={ count:1, getCount:function(){ return this.count; // 1,renturn返回值 } } console.log(User.getCount()); // 1; var func=User.getCount; console.log(func()); // undefined;