js的this到底是什么意思

首先确定一点,this在声明时确定不了,在执行时才知道指向的谁!!!

call() , apply(),bind()  方法的用法

比如下面一个例子:

function  fn(name,age){
    alert(name);
    console.log( this )
}

fn()  //返回的肯定是window对象   因为是window调用的

fn.call({x:100},'zhangsan',12)  //这个this就是指的{x:100} 这个对象,别问为啥,call这个方法的定义就是这个,name就是指的zhangsan,如果还有参数依次往后添加
fn.apply({x:100},['zhangsan',12])  //apply方法和call方法一样,没什么好说的


bind() 方法的使用
var fn = function (name,age){
    alert(name);
    console.log( this )
}.bind({name:"liuzhonghua"})

fn("zhangsan",12);     //这个this指的是{name:"liuzhonghua"   //注意:必须用声明的方式来使用

猜你喜欢

转载自www.cnblogs.com/coder-lzh/p/9189130.html