一、变量作用域和闭包
变量作用域:js是函数级别作用域,在内部的变量内部都能访问,外部不能访问内部的,但是内部能访问外部的
var j = 100;
~(function test(){ // ~把函数转化成表达式
console.log(j);
})();
闭包:
// 闭包
function test(){
var k = 1000;
return function(){
return k;
}
}
var t = test()();
alert(t);
注意:闭包使用不当会造成内存泄漏
二、This指针的使用
1.
// this谁调用指向谁
window.m = 100;
this.n = 200;
function test(){
alert(this.m);
alert(this.n);
}
window.test();
2.
var obj = {
m : 300,
test:function(){
alert(this.m);
}
}
obj.test();
3.
var m =10000;
var obj = {
m : 300,
test:function(){
alert(this.m);
return function(){
alert(this.m); // 这里this指向window
}
}
}
obj.test()();
4.
index.html
<meta charset="utf-8" />
<input type="button" id="test" value="测试" style="color:red;" />
<script src="./scope.js"></script>
scope.js
function test(){
alert(this.style.color);
}
document.getElementById('test').onclick = test;
5.
function test(){
this.a = 1;
}
test.prototype.geta = function(){
return this.a;
};
var p = new test;
console.log(p.geta());