您的位置:首页 > Web前端 > JavaScript

javascript 之this及作用域整理

2015-09-01 23:37 726 查看
在ECMAScript中,只有两种执行环境,全局环境函数环境,每个函数都是一个执行环境,包括嵌套函数。换句话说,其他情况下即使变量声明在一对大括号中,在括号外部仍然可以访问这些变量

for(var i=0; i<5; i++) {
var num = 20; // 在for语句中声明的变量
}
alert(num); // 在for语句外部调用变量,仍然可以得到num的值
<span style="font-size:12px;">var scope = 'top';
var f1 = function() {
console.log(scope);
};
f1(); // 输出 top
var f2 = function() {
var scope = 'f2';
f1();
};
f2(); // 输出 top 而非f2</span>函数作用域的嵌套关系是定义时决定的,而不是调用时决定的,也就 是说,JavaScript 的作用域是静态作用域,又叫词法作用域,
这是因为作用域的嵌套关系可 以在语法分析时确定,而不必等到运行时确定
var div = document.getElementById('elmtDiv');
div.attachEvent('onclick', EventHandler);

function EventHandler()
{
// 在此使用this 为window对象
}这是因为EventHandler只是一个普通的函数,对于attachEvent后,脚本引擎对它的调用和div对象本身没有任何的关系
var div = document.getElementById('elmtDiv');
div.onclick = function()
{
// 在此使用this为div元素对象实例
};
要求成员属性和方法必须使用this关键字来引用
function JSClass()
{
var myName = 'jsclass';
this.m_Name = 'JSClass';
}

JSClass.prototype.ToString = function()
{
alert(myName + ', ' + this.m_Name);
};

var jc = new JSClass();
jc.ToString() //myName is not defined<span style="color: rgb(255, 0, 0); font-family: Consolas, 'Lucida Console', monospace; line-height: 12px; white-space: pre-wrap;"> </span>
<div style="width: expression(this.parentElement.width);
height: expression(this.parentElement.height);">
//this指代指代div元素对象实例本身
对于函数内的变量(包括指向函数的指针变量)来说,this关键字总是指代调用该函数的对象。当单独调用函数时,调用它的对象由window引用;当用var t = new test()方式调用时调用它的对象由t引用。
var scope="global";
function test(){
console.log(scope); // global
}
test();
var scope="global";
function test(){
console.log(scope);  //undefined  why???
var scope="local"
console.log(scope);  //local
}
test();


而Javascript压根没有块级作用域,而是函数作用域.,scope声明覆盖了全局的scope,但是还没有赋值,所以输出:”undefined“。

所谓函数作用域就是说:变量在声明它们的函数体以及这个函数体嵌套的任意函数体内都是有定义的。局部变量在整个函数体始终是由定义的
var scope="global";
function test(){
var scope;
console.log(scope);
scope="local"
console.log(scope);
}
test();

var arg = 2;
function test() {
alert(arg);
this.arg = 1;
}
alert(arg);  //2
test();      //2
alert(arg);  //1
可见函数内的this.arg改变了全局变量的值,也就是现在this指代的是window对象, window.test();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: