<script type = "text/javascript" >
var x = 1;
var y = 0;
var z = 0;
function add(n) {
n = n + 1;
}
y = add(x);
function add(n) {
n = n + 3;
}
z = add(x);
s = y + z;
console.log(y, z, s) //undefined undefined NaN
求: y的值是? z 的值是? s的值是?
我相信,肯定有同学会大意!
我们首先看function add,两个add都没有返回值,而我们知道,没有明确返回值的,全部返回undefined,
所以,y和z都会是undefined,那么s自然也就不会是一个数字了,没错,s应该是NaN
</script>
假如我们将题目改一下呢?如下:
<script type = "text/javascript" >
var x = 1;
var y = 0;
var z = 0;
function add(n) {
return n = n + 1;
}
y = add(x);
function add(n) {
return n = n + 3;
}
z = add(x);
s = y + z;
两个function add都有返回值了,那么,y,z,s会是多少呢?
y和z都是4,s是8,为什么y不是2而是4呢?因为在javascript中,直接通过function申明的函数,
后面定义的,会影响到之前的引用,
</script>
例如,如下:
< script type = "text/javascript" >
function x() {
alert(2)
};
x(); //output 3
function x() {
alert(3)
};
x(); //output 3
< /script>
如果是通过var来申明的函数会是什么情况呢?我们看看:
<script type = "text/javascript" >
var x = function() {
alert(0)
};
x(); //output 0
var x = function() {
alert(1)
};
x(); //output 1
x(); //output 1
</script>
通过var申明的函数,后面定义的并不会影响前面的引用。
如果两种模式混合,又会是什么情况呢?
function blend() {console.log(2)};
blend(); //第22行的函数代码把这个函数覆盖了 所以output 3
var blend = function() { console.log(0)};
blend(); //通过var申明的函数,改变了后来通过function
//申明定义的函数所以output 0
var blend = function() { console.log(1)};
blend(); //通过var申明的函数,覆盖了var声明的function所以output 1
function blend() { console.log(3)};
blend(); //output 1>
// 就像优先级一样 var定义>有名函数
结果是这样的,你猜到了吗?
通过function定义的函数,后面定义的,照旧影响了前面的引用,但是不能改变通过var申明函数后的引用,
反而,通过var申明的函数,改变了后来通过function申明函数之后的引用。
所以,如果:
< script type = "text/javascript" >
var x = function() {
alert(1)
};
x();
function x() {
alert(3)
};
x();
< /script>
后面的x()出来的也会是1。
附加一题,多个相邻的没有设置高度的空元素,margin-bottom和margin-top会相互叠加
<style>
#div1{
border: 10px solid red;
padding: 10px;
overflow: auto;
box-sizing: border-box;
}
#div1 div{
background: blue;
width: 100%;
float: left;
margin: 10px;
line-height: 20px;
}
#div2{
border: 10px solid red;
padding: 10px;
box-sizing: border-box;
}
#div2 div{
background: blue;
line-height: 20px;
margin: 10px 0;
}
</style>
<body>
<div id="div1">
<div>目录</div>
<div>目录</div>
<div>目录</div>
</div>
<div id="div2">
<div>目录</div>
<div>多个相邻的没有设置高度的空元素,margin-bottom和margin-top会相互叠加</div>
<div>目录</div>
</div>
<script>
let height1 = document.getElementById('div1').offsetHeight
let height2 = document.getElementById('div2').offsetHeight
console.log(height1)
console.log(height2)
</script>
</body>