JS函数中的this的四种绑定方式

1. this的默认绑定window

凡是函数作为独立函数调用,没有指定调用对象, 无论位置在哪里,this默认绑定window对象

示例如下:

function test(){
    console.log(this == window);
}
test(); // 打印true
function outFun(){
    function inFun(){
        console.log(this == window);
    }
    inFun();
}
outFun(); // 打印true

2. this的隐式绑定

示例1:

var person = {
    age: 12,
    onTest: function(){
        console.log(this.age);
    }
}
person.onTest(); // 输出12

当函数被一个对象包含的时候,函数的this被隐式的绑定到这个对象, 这时可以通过this访问绑定对象的其他属性

示例2:

function onTest(){
    console.log(this.age);
}
var person1 = {
    age: 12,
    onTest: onTest
}
person1.onTest(); // 输出12
onTest(); // 输出 undefined

person1.onTest() 也可以取到age, 可以看出函数this的绑定并不会因为它被定义在j对象的内部和外部而有任何区别

示例3:

var person2 = {
    age: 12,
    onTest: function(){
        console.log(this.age);
    } 
}
function callTest(fn){
    fn()
}
callTest(person2.onTest); // 输出undefined
  1. 函数this的隐式绑定是动态的
  2. 由于函数的this与对象是动态绑定的, 在对象调佣函数之前函数的this和对象没有强制绑定,函数传递存在this绑定丢失问题

3. this的显示绑定(使用call 和 bind)

var person3 = {
    age: 12,
    onTest: function(){
        console.log(this.age);
    } 
}
function callTest(fn){
    fn.call(person3); // 硬绑定
}
callTest(person3.onTest); // 输出12

使用call() 方法,传递丢失的this绑定成功绑定到person3

var person3 = {
    age: 12,
    onTest: function(){
        console.log(this.age);
    } 
}
var fn = person3.onTest;
fn(); // 输出undefined
var onTest2 = fn.bind(person3);
onTest2(); // 输出12

使用bind() 方法,得到一个this和对象绑定的方法

call和bind的区别是:在绑定this到对象参数的同时

1.call将立即执行该函数

2.bind不执行函数,只返回一个可供执行的函数

4. new绑定

function fun(a){
    this.name = a;
}

var obj1 = new fun('aa');
var obj2 = new fun('bb');

console.log(obj1.name);
console.log(obj2.name);

执行new操作的时候,将创建一个新的对象,并且将构造函数的this指向所创建的新对象

5. 注意

箭头函数:不使用这四个this规则,根据词法作用域来决定this。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值