var和函数的提前声明
1
2
3
4
5
6
7
8
|
function
fn(a) {
console.log(a);
var
a = 2;
function
a() {}
console.log(a);
}
fn(1);
|
输出:function a() {} 2
我们知道var和function是会提前声明的,而且function是优先于var声明的(如果同时存在的话),所以提前声明后输出的a是个function,然后代码往下执行a进行重新赋值了,故第二次输出是2。
给基本类型数据添加属性,不报错,但取值时是undefined
1
2
3
4
5
6
7
|
var
a = 10;
a.pro = 10;
console.log(a.pro + a);
var
s =
'hello'
;
s.pro =
'world'
;
console.log(s.pro + s);
|
答案:NaN undefinedhello
给基本类型数据加属性不报错,但是引用的话返回undefined,10+undefined返回NaN,而undefined和string相加时转变成了字符串。
经典闭包
<!-- 实现一段脚本,使得点击对应链接alert出相应的编号 -->
<meta http-equiv=
"Content-Type"
content=
"text/html; charset=utf-8"
/>
<body>
<a href=
'#'
> 第一个链接 </a> </br>
<a href=
'#'
> 第二个链接 </a> </br>
<a href=
'#'
> 第三个链接 </a> </br>
<a href=
'#'
> 第四个链接 </a> </br>
<script type=
"text/javascript"
>
var
lis = document.links;
for
(
var
i = 0, length = lis.length; i < length; i++) {
(
function
(i) {
lis[i].onclick =
function
() {
alert(i + 1);
};
})(i);
}
</script>
</body>
this
function
JSClass() {
this
.m_Text =
'division element'
;
this
.m_Element = document.createElement(
'div'
);
this
.m_Element.innerHTML =
this
.m_Text;
this
.m_Element.addEventListener(
'click'
,
this
.func);//(答:this
.
func函数里的"this"指向 js.m_Element)
// this.m_Element.onclick = this.func;
}
JSClass.prototype.Render =
function
() {
document.body.appendChild(
this
.m_Element);
}
JSClass.prototype.func =
function
() {
alert(
this
.m_Text);
};
var
jc =
new
JSClass();
jc.Render();
// add div
jc.func(); //(答:这里的“this”指向 jc)
// 输出 division element
//click添加的div元素division element会输出underfined,为什么?
答案:division element undefined
第一次输出很好理解,第二次的话仔细看,this其实已经指向了this.m_Element,因为是this.m_Element调用的addEventListener函数,所以内部的this全指向它了。可以试着加上一行代码this.m_Element.m_Text = ‘hello world’,就会alert出hello world了。