JS中内嵌函数中this关键字的使用
2015-04-17 09:42
218 查看
this关键字的使用
在嵌套函数中:和变量不同,this关键字没有作用域的限制,在嵌套函数的内部使用this关键字可以分为以下两种情况:
1)如果嵌套函数作为方法调用,那么this为当前的上下文。
2)如果当做函数调用,那么this的值依赖于当前使用的是否为严格模式,在非严格模式下,this为全局上下文,否则为undefined.
例如:
var test1={
a:1,
b:2,
fun1:function(){
console.log(“fun1: “ +this); //this为test1对象
function f(){
console.log(“f: “ +this); //this 为undefined 或者全局对象
}
}
}
因此为了能够在函数f中也可以调用上下文的this对象,可以使用通过如下方法解决:
例如
var test1={
a:1,
b:2,
fun1:function(){
console.log(“fun1:this : “ +this); //this为test1对象
var outer = this;
function f(){
console.log(“f:this: “ +this); //this 为undefined 或者全局对象
console.log(“f:outer: ” +outer);//outer则为外层的对象。
}
}
}
这也再次证明了this关键字与作用域的关系。
在嵌套函数中:和变量不同,this关键字没有作用域的限制,在嵌套函数的内部使用this关键字可以分为以下两种情况:
1)如果嵌套函数作为方法调用,那么this为当前的上下文。
2)如果当做函数调用,那么this的值依赖于当前使用的是否为严格模式,在非严格模式下,this为全局上下文,否则为undefined.
例如:
var test1={
a:1,
b:2,
fun1:function(){
console.log(“fun1: “ +this); //this为test1对象
function f(){
console.log(“f: “ +this); //this 为undefined 或者全局对象
}
}
}
因此为了能够在函数f中也可以调用上下文的this对象,可以使用通过如下方法解决:
例如
var test1={
a:1,
b:2,
fun1:function(){
console.log(“fun1:this : “ +this); //this为test1对象
var outer = this;
function f(){
console.log(“f:this: “ +this); //this 为undefined 或者全局对象
console.log(“f:outer: ” +outer);//outer则为外层的对象。
}
}
}
这也再次证明了this关键字与作用域的关系。
相关文章推荐
- JS中内嵌函数中this关键字的使用
- eval 函数使用(js)
- js如何把字符串转为变量使用,以及js下将字符串当函数去执行的方法
- JS中递归函数 JS函数相关及递归函数的使用
- JS中parseINT()函数的使用技巧
- JS 的 _.isEmpty()函数使用
- 关于Qt内嵌CEF使用QString::toStdString();函数导致的一些坑
- js原生态函数中使用jQuery中的 $(this)无效的解决方法
- Js 时间函数getYear()的使用问题探讨
- 使用JS实现jQuery的addClass, removeClass, hasClass函数功能
- js字符串截取函数substr substring slice使用对比
- node.js使用require()函数加载模块
- JS基础——函数的创建和使用
- 使用js Math.random()函数生成n到m间的随机数字
- 使用js Math.random()函数生成n到m间的随机数字
- 在JS中使用Freemaker变量值,利用函数js_string
- JS基础——函数的创建和使用
- JS解决chrome37+ window.showmodaldialog函数不能使用的问题
- 使用JS实现jQuery的addClass, removeClass, hasClass函数功能
- JS常用函数使用指南