javascript中的变量范围是什么?它们的内部是否与函数外部相同?或者甚至重要吗?另外,如果变量是全局定义的,那么它们存储在哪里?
我在几篇文章和博客中看到了对curried函数的引用,但我找不到一个好的解释(或者至少有一个有意义的解释!)
规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.
ES2015中的箭头功能提供了更简洁的语法.我现在可以用箭头功能替换所有函数声明/表达式吗?我需要注意什么?
例子:
构造函数
function User(name) {
this.name = name;
}
// vs
const User = name => {
this.name = name;
};
Run Code Online (Sandbox Code Playgroud)
原型方法
User.prototype.getName = function() {
return this.name;
};
// vs
User.prototype.getName = () => this.name;
Run Code Online (Sandbox Code Playgroud)
对象(文字)方法
const obj = {
getName: function() {
// ...
}
};
// vs
const obj = {
getName: () => {
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
回调
setTimeout(function() {
// ...
}, 500);
// vs
setTimeout(() => {
// ...
}, …Run Code Online (Sandbox Code Playgroud) 我坚持使用'返回函数的函数'这个概念.我指的是Stoyan Stefanov撰写的"面向对象的Javascript"一书.
片段一:
function a() {
alert('A!');
function b(){
alert('B!');
}
return b();
}
var s = a();
alert('break');
s();Run Code Online (Sandbox Code Playgroud)
输出:
A!
B!
break
Run Code Online (Sandbox Code Playgroud)
小片二
function a() {
alert('A!');
function b(){
alert('B!');
}
return b;
}
var s = a();
alert('break');
s();Run Code Online (Sandbox Code Playgroud)
A!
break
B!
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我返回b和b()上面的片段之间的区别吗?
我正在阅读Eloquent JavaScript(新版本),并且我在更高阶函数上达成了一部分,我对以下代码中发生的事情感到困惑.
function noisy(f) {
return function(arg) {
console.log("calling with", arg);
var val = f(arg);
console.log("called with", arg, "- got", val);
return val;
};
}
noisy(Boolean)(0);
// ? calling with 0
// ? called with 0 - got false
Run Code Online (Sandbox Code Playgroud)
为什么这个函数的调用会像这样嘈杂?(布尔)是演员吗?为什么演员?返回值?还是论点?为什么不(布尔值)嘈杂(0)如果它的返回值.或者噪声((布尔值)0)如果参数是被转换的参数.
noisy(Boolean)(0)
Run Code Online (Sandbox Code Playgroud)这一行发生了什么?f()甚至定义在哪里?
var val = f(arg);
Run Code Online (Sandbox Code Playgroud)我理解回调函数的本质在于,该函数作为参数传递给另一个函数后会再次执行。但是,我对回调函数中的变量来自何处感到困惑,如下面的 node.js 示例所示:
router.get('/', function(req, res){
res.render('index', {});
});
Run Code Online (Sandbox Code Playgroud)
变量 req 和 res 是如何填充的?一个解释我如何只调用 res.render(...) 而不声明 res 自己的例子将不胜感激。
javascript ×5
function ×2
currying ×1
definition ×1
ecmascript-6 ×1
node.js ×1
scope ×1
terminology ×1
var ×1
variables ×1