Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Master #21

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

Open
sunshinewu wants to merge 2 commits into RobinQu:master
base: master
Choose a base branch
Loading
from sunshinewu:master
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion chapters/JavaScript_Core/JavaScript_Basics/Function.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ JavaScript函数对象的内部状态不仅包含着函数的代码逻辑,还
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (i) {
return function(e){
alert(e);
alert(i); //should not be alert(e);
};
}(i);
}
Expand All @@ -206,6 +206,23 @@ JavaScript函数对象的内部状态不仅包含着函数的代码逻辑,还

这里使用一个立即执行函数并传递当前的i的值,返回一个新生成的函数。在这个新生成的函数的闭包中就保存了当前的i的值。

除了这样,还能将其完善得更优雅一些么?当然!我们还可以先在循环之外创建一个辅助函数,让这个辅助函数再返回一个绑定了当前i值的函数,这样则可以避免在循环中创建函数而带来无谓的计算&混淆。


var add_the_handlers = function (nodes) {
var i;
var helper = function (j) {
return function (e) {
alert(j);
};
};
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = helper(i);
}
};



## 函数中的this对象

在一个对象中的this始终引用当前对象,但是在函数中,特别是在闭包中,this有一些特殊的行为。
Expand Down

AltStyle によって変換されたページ (->オリジナル) /