1. 程式人生 > 其它 >JavaScript ES6 - 函式的建立方式與呼叫方式及其指向

JavaScript ES6 - 函式的建立方式與呼叫方式及其指向

        // 函式的不同調用方式決定了this 的指向不同
        // 1. 普通函式 this 指向window
        function fn() {
            console.log('普通函式的this' + this);
        }
        window.fn();
// 2. 物件的方法 this指向的是物件 o var o = { sayHi: function() { console.log('物件方法的this:' + this); } } o.sayHi();
// 3. 建構函式 this 指向 ldh 這個例項物件 原型物件裡面的this 指向的也是 ldh這個例項物件 function Star() {}; Star.prototype.sing = function() { } var ldh = new Star();
// 4. 繫結事件函式 this 指向的是函式的呼叫者 btn這個按鈕物件 var btn = document.querySelector('button'); btn.onclick = function() { console.log(
'繫結時間函式的this:' + this); };
// 5. 定時器函式 this 指向的也是window window.setTimeout(function() { console.log('定時器的this:' + this); }, 1000);
// 6. 立即執行函式 this還是指向window (function() { console.log('立即執行函式的this' + this); })(); </script>