首页 > web前端 > js教程 > 正文

js执行上下文 变量、函数、this

不言
发布: 2018-07-05 17:25:21
原创
2020 人浏览过

这篇文章主要介绍了关于js执行上下文 变量、函数、this ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

JavaScript 中的执行上下文和调用栈

ES6 变量作用域与提升:变量的生命周期详解

变量提升

  • 变量的定义在代码预解析时,在作用域顶部定义

  • 无 var 没有变量提升

console.log(a);  // undefined,如果没有定义会直接报错
var a = 'aaa';
console.log(a);  // aaa

// 下面代码全等于上面代码
var a;  // 变量提升,函数作用域范围内
console.log(a);  // undefined
a = 'aaa';
console.log(a);  // aaa

console.log(a);  // 直接报错
a = 'aaa';
登录后复制

函数提升

  • 函数的定义在代码预解析时,在作用域顶部定义

  • 函数赋值在作用域顶部

console.log(f1);  // f1() { console.info('函数'); }
var f1 = function() { console.info('变量'); }
console.log(f1);  // ƒ () { console.info('变量'); }
function f1() { console.info('函数'); }
console.log(f1);  // ƒ () { console.info('变量'); }

// 下面代码全等于上面代码
var f1;  // 定义提升
function f1() { console.info('函数'); }  // 函数顶部赋值
console.log(f1);  // f1() { console.info('函数'); }
f1 = function() { console.info('变量'); }
console.log(f1);  // ƒ () { console.info('变量'); }
console.log(f1);  // ƒ () { console.info('变量'); }
登录后复制

函数上下文关系

  • 函数的上下文关系在定义时确定

var scope = "global scope";
function checkscope() {
  var scope = "local scope";
  function f() { return scope; }
  return f;
}
checkscope()();  // local scope
登录后复制

this 上下文关系

  • this 的上下文关系在执行时确定

正常函数调用,this 指向 window

// 在 function 里
function test() {
    var type = this === window;
    return type;
}
test();  // true
登录后复制

方法调用,this 指向调用对象

// 在对象里
var obj = {
    test: function() {
        var type = this === obj;
        return type;
    }
};
obj.test();  // true

// 在 prototype 对象的方法中
function obj() {
}
obj.prototype.test = function() {
    return this;
}
var o = new obj();
o.test() === o;  // true
登录后复制

构造器函数调用,this 指向 new 生成的对象

// 调用 new 构造对象时
function obj() {
    this.test = function() {
        return this;
    }
}
var o = new obj();
o.test() === o;  // true
登录后复制

apply / call 调用

function test() {
    return this;
}
var o = {};

// apply
test.apply(o) === o;  // true

// call
test.call(o) === o;  // true
登录后复制

dom 的事件属性中

// 点击后输出 true
<input id="a" type="text" onclick="console.info(this === document.getElementById(&#39;a&#39;))" />

// 点击后输出 true
<input id="a" type="text" />
<script type="text/javascript">
    document.getElementById(&#39;a&#39;).addEventListener("click", function(){
        console.info(this === document.getElementById(&#39;a&#39;));
    });
</script>

// 点击后输出 true
<input id="a" type="text" />
<script type="text/javascript">
    document.getElementById(&#39;a&#39;).onclick = function(){
        console.info(this === document.getElementById(&#39;a&#39;));
    });
</script>
登录后复制

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!  

相关推荐:

JS与JQ实现焦点图轮播效果

js实现点击按钮可实现编辑

关于JS 继承的介绍

以上是js执行上下文 变量、函数、this的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!