javascript中的this

js中的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。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值