s中的this总是让人,是js众所周知的坑之一。
总结一下,this的坑分为5种。
1.全局代码中的this。
alert(this);//window
全局范围内this将会全局,在浏览器window

2.作为单纯函数调用

function foo(x){
    this.x = x;
}
foo(99);
alert(x);//全局变量x值为99

 

 

这里this指向全局对象,就是window。在严格模式中,则undefiend。

3.作为对象的方法调用

var name = "xiaoming";
var person = {
    name:"xiaohong",
    hello:function(sth){
        console.log(this.name + "says" + sth);
    }
}
person.hello("hello world");

 

输出 xiaohong says hello world。this指向person对象,即当前对象。

4.作为构造函数
new Foo();
function Foo(){
this.name = “fooname”;
}
构造函数内部的this指向新创建的对象

5.内部函数

var name = "xiaoming";
var person = {
    name:"xiaohong",
    hello:function(sth){
        var sayhello = function(sth){
            console.log(this.name + "says" + sth);
        }
        sayhello(sth);
    }
}
person.hello("hello world");

 

 

在内部函数中,this没有按预想的绑定到外层函数对象上,而是绑定到了全局对象。这里普 遍被认为是 JavaScript语言的设计错误,因为没有人想让内部函数中的 this指向全局对象。 一般的处理方式是将 this作为变量保存下来,一般约定为 that或者 self

var name = "xiaoming";
var person = {
    name:"xiaohong",
    hello:function(sth){
        var that = this;
        var sayhello = function(sth){
            console.log(that.name + "says" + sth);
        }
        sayhello(sth);
    }
}
person.hello("hello world");

 

6.使用call和apply设置this 

person.hello.call(person, “world”);
apply和 call类似,只是后面的参数是通过一个数组传入,而不是分开传入。两者的方法定义:
call(thisArg[,arg1,arg2,…]); // 参数列表,arg1,arg2,…
apply(thisArg [,argArray] ); // 参数数组,argArray
两者都是将某个函数绑定到某个具体对象上使用,自然此时的 this会被显式的设置为第一 个参数。

我们可能经常会写这样的代码:
$(“#ele”).click=obj.handler;

如果在 handler中用了 this,this会绑定在 obj上么?显然不是,赋值以后,函数是在回调中执行的,this会绑定到$(“#ele”)元素上。
这边介绍一个bind方法

var name = "xiaoming";
        var person = {
            name:"xiaohong",
            hello:function(sth){
                var that = this;
                var sayhello = function(sth){
                    console.log(that.name + "says" + sth);
                }
                sayhello(sth);
            }
        }

var odiv = document.getElementById("odiv");
odiv.onclick=person.hello.bind(person,"hello world");//xiaohong says hello world

 

bind方法和call/apply方法一样,不同的就是bind方法不执行,只是拷贝代码。用这个方法可以改变this指向,this指向的不再是odiv而是person。


web前端/H5/javascript学习群:250777811
欢迎大家关注我的微信号公众号,公众号名称:web前端EDU。扫下面的二维码或者收藏下面的二维码关注吧(长按下面的二维码图片、并选择识别图中的二维码)