前言
javascript 的 this 指向主要是依賴背景關系物件決定,箭頭函式例外,
默認系結
在全域作用域下呼叫函式,函式的this默認指向window,
注意1:嚴格模式下,默認指向undefined
function test() {
console.log(this.a);
}
var a = 1;
test(); // 1
// 嚴格模式
function test() {
'use strict';
console.log(this.a);
}
var a = 1;
test(); // TypeEror 報錯
注意2:全域作用域下 var宣告的變數會默認系結到window,而let、const宣告的變數不會
let a = 1;
var b = 1;
window.a // undefined
window.b // 1
隱式系結
當函式參考有背景關系物件時,this隱式系結到這個背景關系物件中,
function test() {
console.log(this.a);
}
var obj = {
a: 1,
test: test
}
var a = 2;
obj.test(); // 1
隱式丟失
function test() {
console.log(this.a);
}
var obj = {
a: 1,
test: test
}
var a = 2;
// 隱式丟失,this 應用默認系結規則
var bar = obj.test;
bar() // 2
顯式系結
call、apply、bind等顯式改變this指向,
注意:非嚴格模式下,call、apply、bind等傳入null、undefined會默認轉為window
function test() {
console.log(this.a);
}
var obj = {
a: 1
}
var a = 2;
test(); // 2
test.call(obj); // 1
test.apply(obj); // 1
var bTest = test.bind(obj);
bTest(); // 1
注意2:多次使用bind,this只會指向第一次bind的this
function test() {
console.log(this.a);
}
var obj1 = { a: 1 }
var obj2 = { a: 2 }
var obj3 = { a: 3 }
var bind1 = test.bind(obj1);
bind1(); // 1
var bind2 = bind1.bind(obj2);
bind2(); // 1
var bind3 = bind2.bind(obj3);
bind3(); // 1
內置函式改變this指向
function test() {
console.log(this.a);
}
var obj = {
a: 1
}
var arr = [1, 2, 3];
arr.forEach(test, obj); // 列印 3 個 1
new 系結
使用new運算子會產生如下步驟:
- 創建一個新的空物件,
- 將新物件與建構式的
prototype相連, - 新物件系結帶建構式的
this, - 如果建構式有回傳值,且回傳值是物件,則回傳建構式的回傳值,否則回傳新建的物件,
function create() {
let obj = new Object();
let constructor = [].shift.call(arguments);
// obj.__proto__ = constructor.prototype;
Object.setPrototypeOf(obj, constructor.prototype);
// 改變 this
let res = constructor.apply(obj, arguments);
const isObj = Object.prototype.toString.call(res) === '[object Object]';
return isObj ? result : obj;
}
箭頭函式
箭頭函式比較特殊,它有以下幾個特點:
-
沒有自身的
this,在定義時默認系結父級作用域的this,即采用詞法作用域系結this. -
沒有原型
prototype,無法使用 new 運算子,即不能作為建構式. -
無法使用
call、apply、bind等顯式改變其this.const test = () => console.log(this); let obj = {}; test(); // window test.call(obj); // window const foo = test.bind(obj); foo(); // window
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/17844.html
標籤:其他
上一篇:html包含html檔案的方法
下一篇:ng-專案結構
