this指針
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>this指針</title>
</head>
<body>
<script>
window.onload = function(){
// 默認:在嚴格模式下綁定到undefined,否則綁定到全局對象。
function demo(){
console.log(this);// Window
}
demo();
function demo2(){
"use strict"
console.log(this);// undefined
}
demo2();
var o = {};
o.name = "xxx";
o.print = function() {
console.log(this.name); // xxx 指向上下文對象o
}
o.print();
function Demo3(name){
this.name = name;
console.log(this.name);// yyy 由new調用 指向新創建的對象
}
new Demo3("yyy");
num = 1;
var obj = {
num: 2,
print: function() {
this.num = 3;
console.log(this.num); // 3 指向上下文對象obj
(function(){
console.log(this.num); // 1 沒有調用者 指向全局
})();
}
}
obj.print(); // 由上下文調用:綁定到上下文對象
var obj2 = {
num: 5
};
Demo4.call(obj2,"ddd");
function Demo4(name) {
this.name = name;
console.log(this); // {num: 5, name: "ddd"} 由call、apply調用:綁定到指定對象
}
// 總結:
// 1.默認綁定:嚴格模式下綁定到undefined,否則綁定到全局對象
// 2.由new調用:綁定到新創建的對象
// 3.由call、apply調用:綁定到指定對象
// 4.由上下文對象調用:綁定到上下文對象
}
// 一定要注意,有些調用可能在無意中使用默認綁定規則
// 如果想更安全的忽略this綁定,可以使用一個空對象 比如 ø = Object.create(null); 以保護全局對象
// ES6中的箭頭函數並不會使用四條標準的綁定規則,而是根據當前的詞法作用域來決定this
// 具體來說,箭頭函數會繼承外層函數調用的this綁定(無論this綁定到什麼)
// 如果箭頭函數外層沒有函數,綁定到全局,如果箭頭函數外層有函數 綁定到外層函數調用的this
// 這其實和ES6之前代碼中的self = this;機制一樣
n = 2;
var obj2 = {
n: 1,
print: function(){
console.log(this.n); // 綁定到上下文對象obj2
},
print2: ()=>{
console.log(this.n); // 綁定到外層函數obj2調用的this綁定 在這裏是window
}
}
obj2.print(); // 1
obj2.print2(); // 2
console.log(this.obj2); // {n: 1, print: ƒ, print2: ƒ}
var o1 = {
m:1,
print:function(){
(()=>{
console.log(this.m); // 綁定到外層函數print調用的this綁定 在這裏是o1
})()
}
}
o1.print();
</script>
</body>
</html>