js执行上下文变量、函数、this
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了js执行上下文变量、函数、this,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2780字,纯文字阅读大概需要4分钟。
内容图文
这篇文章主要介绍了关于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('a'))" /> // 点击后输出 true <input id="a" type="text" /> <script type="text/javascript"> document.getElementById('a').addEventListener("click", function(){ console.info(this === document.getElementById('a')); }); </script> // 点击后输出 true <input id="a" type="text" /> <script type="text/javascript"> document.getElementById('a').onclick = function(){ console.info(this === document.getElementById('a')); }); </script>
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
JS与JQ实现焦点图轮播效果
js实现点击按钮可实现编辑
关于JS 继承的介绍
以上就是js执行上下文 变量、函数、this的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的js执行上下文变量、函数、this全部内容,希望文章能够帮你解决js执行上下文变量、函数、this所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。