JavaScript函数重载/覆盖
我在努力理解JavaScript函数重载/覆盖,javascript,oop,overloading,Javascript,Oop,Overloading,我在努力理解 function test() { return 'foo'; } console.log(test()); test = function() { return 'bar'; } console.log(test()); function test(a, b) { return 'baz'; } console.log(test()); console.log(test(true)); console.log(test(1, 2)); 上面的代码是什么 b
function test() {
return 'foo';
}
console.log(test());
test = function() {
return 'bar';
}
console.log(test());
function test(a, b) {
return 'baz';
}
console.log(test());
console.log(test(true));
console.log(test(1, 2));
上面的代码是什么
baz酒吧
酒吧
酒吧
酒吧 但是JavaScript是一种单线程语言,也是我所期待的函数重载概念 foo
酒吧
酒吧
baz
巴兹
有人能解释为什么会发生这种情况吗?Javascript函数不能有重载,它们只是被覆盖。要获得相同的效果,需要区分方法中的不同重载
function test(a, b) {
if(b)
return 'baz';
return 'foo';
}
是的。我认为发生的情况如下:
函数测试(…){…}
声明的函数被提升到当前范围的顶部。因此,使用该语法的函数的两个定义都被提升到顶部,但第二个定义覆盖了第一个定义,因此结果为“baz”test=Function(…){…}
。因此,当您将标识符test
重新分配给该函数表达式时,它将成为脚本其余部分的test
的值让myFn=function(…){…}
按照我的理解,这是一行一行的:
// `test` defined with func declaration, hoisted to top
function test() {
return 'foo';
}
console.log(test);
console.log(test());
// `test` overwritten with function expression, hoisting has already occurred,
// `test` identifier will have this value for remainder of script
test = function() {
return 'bar';
}
console.log(test);
console.log(test());
// `test` overwritten with new func declaration, hoisted to top, but after first declaration
function test(a, b) {
return 'baz';
}
console.log(test);
console.log(test());
console.log(test(true));
console.log(test(1, 2));
逐步:
function test() {
return 'foo';
}
这是一个函数声明。test
变量在运行前解释时声明
test = function() {
return 'bar';
}
这是一个函数表达式。执行此行时,test
变量将被覆盖
function test(a, b) {
return 'baz';
}
这是另一个函数声明。test
变量在运行前再次被覆盖
test = function() {
return 'bar';
}
这就是为什么您的第一个版本的测试函数从未被调用。因为第二个函数声明在运行前重写了它
test = function() {
return 'bar';
}
但这并不能完全解释发生了什么。您是否愿意更新您的答案,以便逐行逐步给出答案?e、 g.功能已声明和提升;功能被声明和提升,覆盖;调用第二个函数;声明的函数被函数表达式等覆盖。