犀牛书上说javascript中的函数是通过词法来划分作用域的,也就是函数在定义的作用域里运行。但是property框架的说明文档怎么说是动态作用域?
<script language="javascript">
window.name = "the window object";
function scopeTest() {
var name="helloworld";
//return this.name
return (function(){return this.name})();
}
alert(scopeTest());
</script>这个例子,按我的理解,应该是弹出helloworld才对,为什么弹出的是the window object?
因为javascript中this指针指向的是定义函数的那个作用域,那return this.name中this应该指向scopeTest的调用对象,所以this.name=“helloworld“window.name="the window object";
var foo = {
name: "the foo object!",
otherScopeTest: function() {
return this.name
}
}
foo.otherScopeTest()返回的为什么是the foo object?哪位大侠解释解释
<script language="javascript">
window.name = "the window object";
function scopeTest() {
var name="helloworld";
//return this.name
return (function(){return this.name})();
}
alert(scopeTest());
</script>这个例子,按我的理解,应该是弹出helloworld才对,为什么弹出的是the window object?
因为javascript中this指针指向的是定义函数的那个作用域,那return this.name中this应该指向scopeTest的调用对象,所以this.name=“helloworld“window.name="the window object";
var foo = {
name: "the foo object!",
otherScopeTest: function() {
return this.name
}
}
foo.otherScopeTest()返回的为什么是the foo object?哪位大侠解释解释
name: "the foo object!",
otherScopeTest: function() {
return this.name
}
}
window.test=foo.otherScoptTest;
test();
test返回的怎么就变成了the window object
在第一个例子中,scopeTest是Function对象,是没有自己的作用域的,它的作用域绝对与调用它的对象//下面说明了在window下调用此函数的作用域情况
function scopeTest() {
var name="helloworld"; //作用域window,此句定义的name变量因为没有被引用,所以生存周期在scopeTest调用完成后就结束了return (function(){return this.name})();//作用域window} //scopeTest() 的结果相当于返回一个自运行的匿名函数既(function(){return this.name})();其调用者还是window对象,所以返回the window object
(function(){
return this.name; //作用域window
})()第二个例子中,由于foo.otherScoptTest是个函数而window.test=foo.otherScoptTest使其调用者变为window对象,所以其作用域为windowvar foo = {
name: "the foo object!",
otherScopeTest: function() {
return this.name
}
}
window.test=foo.otherScoptTest;
test();
对你的这个解释不理解,这个应该算是定义了一个嵌套函数,根据作用域链原理,那现在的作用域应该是
window scope-> scopeTest函数执行时形成的调用对象作用域->匿名函数的调用对象,在函数中,this关键字应该指向他的上层作用域,也就是在匿名函数中,this应该指向scopeTest函数形成的作用域才对?第二个例子中,由于foo.otherScoptTest是个函数而window.test=foo.otherScoptTest使其调用者变为window对象,所以其作用域为window
记得javascript是遵守词法作用域规则,也就是说它在定义的地方执行,那如果调用者变成window,作用域就变成window,不是动态作用域吗?
不知道我的理解哪里出了问题谢谢你的回答。
var name="helloworld"; //而且这里用的是var的声明的方式,就算是个对象,也不能用this.name来获取name值
//return this.name
return (function(){return this === window})();
}
alert(scopeTest()); //true2.作用域这东西是可以通过apply,call等方法改变,是算静态还是动态,说不清楚
个人意见,可能有些表达不是很清楚,欢迎指正