Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS中this分析 #9

Open
dashengzi66 opened this issue Apr 20, 2021 · 0 comments
Open

JS中this分析 #9

dashengzi66 opened this issue Apr 20, 2021 · 0 comments

Comments

@dashengzi66
Copy link
Owner

dashengzi66 commented Apr 20, 2021

this:函数执行的主体(谁执行的函数)

  • 事件绑定
  • 函数执行(普通函数执行、成员访问、匿名函数、回调函数)
  • 构造函数
  • 箭头函数(生成器函数generator)
  • 基于call/apply/bind强制修改this指向

全局上下文中的this:window
块级上下文中没有自己的this,所有的this都是继承上级上下文中的this(箭头函数也是)

事件绑定

  • DOM0:xxx.onxxx=function(){}
  • DOM2:
    xxx.addEventListener('xxx',function(){})
    xxx.attachEvent('onxxx',function(){})
    给当前元素的某个事件行为绑定方法(此时是创建方法,方法没执行),当事件行为触发,浏览器会把绑定的函数执行,此时函数中的this->当前元素对象本身
    特殊:基于attachEvent实现事件绑定,方法执行,方法中的this是window
    document.body.addEventListener('click',function(){console.log(this);})//->body

函数执行

正常的普通函数执行:看函数执行前是否有“点”,如果有“点”,“点”前面是谁this就是谁,没有this是window(严格模式下是undefined)

function fn() {
  console.log(this);
}
let obj = {
  name:'asever6',
  fn
}
fn();//this->window
obj.fn();//this-obj

匿名函数:
 函数表达式:等同于普通函数或者事件绑定等机制
 自执行函数:this一般都是window/undefined
 (function(x){console.log(this)})(10);//window/undefined
 回调函数:一般都是window/undefined,但是如果在函数执行中,对回调函数的执行做了特殊处理,以自己的处理为主
括号表达式:小括号中包含“多项”,这样也只取最后一项,但是this受到影响(一般是window/undefined)
 (obj.fn)();//this->obj
 (10,obj.fn)();//this->window(严格模式下是undefined)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant