We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
看您的学习记录里面有这么一段代码,运行跟注释不符,我想知道怎么用才能正确,谢谢! `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`
The text was updated successfully, but these errors were encountered:
这里确实有问题,函数不是构造函数,没有 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
Sorry, something went wrong.
谢谢,看了您的学习笔记,对我扩展知识广度帮助很大,感谢!
No branches or pull requests
看您的学习记录里面有这么一段代码,运行跟注释不符,我想知道怎么用才能正确,谢谢!
`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`
The text was updated successfully, but these errors were encountered: