首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

javascript中的this绑定

this是一个关键字,表示执行当前函数的对象

this永远跟着当前函数走,

永远是一个对象,

永远在函数执行时才能确定。

1. 默认绑定:没有明确被隶属对象执行的函数,this指向window

function fn(){ console.log(this); //window console.log(typeof this); //object}fn();

严格模式下,this指向undefiend

"use strict";function fn(){ console.log(this); //undefined}fn();

2. 隐式绑定:明确被隶属对象执行的函数,this指向执行对象

var obj = { fn:function(){ console.log(this); }}obj.fn(); //this指向obj

隐式丢失:某函数被当做参数传递给另一个函数,则会丢失原本的执行对象,指向window

var obj = { fn:function(){ console.log(this); }}function test(cb){ cb();}test(obj.fn); //this指向window

注意:不是所有的回调函数中this都指向window,某些特定情况下被系统修改了。

document.addEventListener("click",function(){ console.log(this); //this指向document});

3. 显示绑定(强制绑定):利用函数的方法改变this的指向(解决了this隐式丢失的问题)

例1:

function fn(a){ console.log(this); console.log(typeof this); //object}fn.call("hello"); //this指向hello

例2:针对上方隐式绑定的隐式丢失问题,可以这样解决

4. new绑定:函数被new执行后,函数内部的this指向new出的实例

function Fn(){ console.log(this); console.log(typeof this); //object}new Fn(); //this指向Fn{}

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200421A05ILW00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券