这篇文章主要介绍了关于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 scopethis 的上下文关系在执行时确定
函数是一组语句一起执行任务。在MATLAB中,函数定义在单独的文件。文件函数的文件名应该是相同的。 函数操作在自己的工作空间,它也被称为本地工作区,独立的工作区,在 MATLAB 命令提示符访问,这就是所谓的基础工作区的变量。函数可以接受多个输入参数和可能返回多个输出参数 。 MATLAB是MathWorks公司开发的一种编程语言。它最初是一个矩阵的编程语言,使线性代数编程很简单。它可以运行在交互式会话和作为批处理作业。有需要的朋友可以下载看看
1
// 在 function 里
function test() {
var type = this === window;
return type;
}
test(); // true// 在对象里
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// 调用 new 构造对象时
function obj() {
this.test = function() {
return this;
}
}
var o = new obj();
o.test() === o; // truefunction test() {
return this;
}
var o = {};
// apply
test.apply(o) === o; // true
// call
test.call(o) === o; // true// 点击后输出 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执行上下文 变量、函数、this的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号