javascript中this的用法
this的用法分几种情况
1)如果调用this的function是对象的方法时(任何用作方法的函数都有效地传递了一个隐式的参数this,this指向调用函数的对象。
如:
- var a = {
- arg1: 1,
- arg2: 2,
- m : function(){
- return this.arg1 + this.arg2; // 此处this指向a对象
- }
- }
2)如果调用this的function只作为一个function存在时(一个函数作为函数儿不是方法调用的时候),this指向全局变量
- function a(){
- this.arg1 = 2; //此处this指向window
- }
值得注意的是,函数嵌套,this同样指向window:
- function a(){
- this.arg1 = 2; //此处this指向window
- function b(){
- console.log(this)// 此处this同样指向window
- }
- }
3)当一个函数嵌套在另外一个作为方法的函数里面是,前者的this(包括后者的this)都指向调用后者这个函数的对象
- var b = {
- arg1: 1,
- arg2: 2,
- m : function(){
- function emb(){
- alert(this.arg1); //此处this指向b对象
- }
- }
- }
只为成功找方法,不为失败找理由!