首頁  >  文章  >  web前端  >  js執行上下文 變數、函數、this

js執行上下文 變數、函數、this

不言
不言原創
2018-07-05 17:25:212012瀏覽

這篇文章主要介紹了關於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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn