它们之间有什么区别吗? 我已经使用了这两种方法,但不知道哪个做什么以及哪个更好?
function abc(){
// Code comes here.
}
abc = function (){
// Code comes here.
}
在定义这些函数时有什么区别吗?比如i++和++i之间?
它们之间有什么区别吗? 我已经使用了这两种方法,但不知道哪个做什么以及哪个更好?
function abc(){
// Code comes here.
}
abc = function (){
// Code comes here.
}
在定义这些函数时有什么区别吗?比如i++和++i之间?
function abc(){
// Code comes here.
}
将被提升。
abc = function (){
// Code comes here.
}
不会被提升。
例如,如果您执行以下操作:
abc();
function abc() { }
由于 abc
被提升到了封闭作用域的顶部,所以代码会运行。
但如果你这样做:
abc();
var abc = function() { }
abc
已经被声明,但没有赋值,因此无法使用。
哪种方式更好更多地是编程风格的争论。
http://www.sitepoint.com/back-to-basics-javascript-hoisting/
abc
尚未声明,不能使用。”变量声明也会被提升,因此变量已经被声明,但它还没有值。 - Felix Kling简短回答:没有。
您正在将函数放入全局命名空间中。任何人都可以访问它,任何人都可以覆盖它。
更安全的标准方法是将所有内容包装在自调用函数中:
(function(){
// put some variables, flags, constants, whatever here.
var myVar = "one";
// make your functions somewhere here
var a = function(){
// Do some stuff here
// You can access your variables here, and they are somehow "private"
myVar = "two";
};
var b = function() {
alert('hi');
};
// You can make b public by doing this
return {
publicB: b
};
})();
html
标签?这个问题和 HTML 没有任何关系! - Felix Klingjavascript
。很明显它与Java无关。如果有人不知道JavaScript和Java之间的区别,那么他们不应该从事编程。 - Felix Kling