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

您好,看了您的学习记录,有点问题 #1

Closed
alphagege opened this issue Dec 29, 2020 · 2 comments
Closed

您好,看了您的学习记录,有点问题 #1

alphagege opened this issue Dec 29, 2020 · 2 comments

Comments

@alphagege
Copy link

看您的学习记录里面有这么一段代码,运行跟注释不符,我想知道怎么用才能正确,谢谢!
`var a = 5

function callback() {
var a = 1
console.log('-- callback this', this, this.a, '--')
}
function validate() {
var a = 2
console.log('-- validate this', this, this.a, '--')
}
function showPrompt(title, validate, callback) {
validate() // 打印 5
callback() // 打印 5
}
showPrompt('1', validate, callback) // 5 5
showPrompt('1', validate.bind(validate), callback.bind(callback)) // 2 1`

@dev-zuo
Copy link
Owner

dev-zuo commented Dec 30, 2020

这里确实有问题,函数不是构造函数,没有 new,调用时 this 都是指向 window。不会打印函数内对应的变量 a

应该改为

var a = 5
function callback() {
  console.log('-- callback this', this, this.a, '--')
}
function validate() {
  console.log('-- validate this', this, this.a, '--')
}
function showPrompt(title, validate, callback) {
  validate()
  callback()
}
showPrompt('1', validate, callback) // 5 5 
showPrompt('1', validate.bind({a: 2}), callback.bind({a: 1})) // 2 1

或者

var a = 5
var callback = {
  a: 1,
  handler() {
    console.log(this, this.a)
  }
}
var validate = {
  a: 2,
  handler() {
    console.log(this, this.a)
  }
}
function showPrompt(title, validate, callback) {
  validate()
  callback()
}
showPrompt('1', validate.handler, callback.handler) // 5 5 
showPrompt('1', validate.handler.bind(validate), callback.handler.bind(callback)) // 2 1

@dev-zuo dev-zuo closed this as completed Dec 30, 2020
@alphagege
Copy link
Author

谢谢,看了您的学习笔记,对我扩展知识广度帮助很大,感谢!

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

2 participants