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

关于 this 的两个题 #36

Open
yyzclyang opened this issue Aug 18, 2019 · 0 comments
Open

关于 this 的两个题 #36

yyzclyang opened this issue Aug 18, 2019 · 0 comments

Comments

@yyzclyang
Copy link
Owner

this 是参数,是一个隐式参数。

new 重新设计了 this,箭头函数不接受 this

  • 显式的 this

fn.call(asThis, 1, 2)
fn.bind(asThis, 1, 2)()
obj.method.call(obj, 1, 2)

  • 隐式的 this

fn(1, 2) //fn.call(undefined, 1, 2)
obj.method(1, 2) //obj.method.call(obj, 1, 2)
array[0](1, 2) //array[0].call(array, 1, 2)

测试 showtime

例子 1

button.onclick = funtion() {
  console.log(this)
}

this 是什么?是点击的元素吗?

No

要看是如何调用的。

如果是点击按钮触发,this 是点击的元素,如果是这样调用呢?

const fn = button.onclick;
fn(); // this 为 window

button.onclick.call(undefined) // this 为 window

例子 2

let length = 10;
function fn(){
  console.log(this.length);
}
let obj = {
  length: 5,
  method(fn){
    fn();
    arguments[0]();
  }
}  
obj.method(fn, 1) 
  • 先看 fn()

先改写为 call

let length = 10;
function fn(){
  console.log(this.length); // this 为 window
}
let obj = {
  length: 5,
  method(fn){
    fn.call(undefined);
  }
}
obj.method(fn, 1)

可以看到 fn() 执行的时候 thiswindow,但是 let 声明的变量不会挂到 window 上,const 也不会,var 会。

windowlength 默认为当前窗口中包含的框架数量(框架包括 frameiframe 两种元素)。参考链接

  • 再看 arguments[0]()

先改写 call

let length = 10;
function fn(){
  console.log(this.length); // this 为 arguments
}
let obj = {
  length: 5,
  method(fn){
    arguments[0]() ; // 输出 2
    // -> arguments.0.call(arguments)
    // -> fn.call(arguments)
  }
}  
obj.method(fn, 1)

可以看到 fnthisargumentsargumentslength实参的长度。也就是 (fn, 1) 的长度 2。

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