this指標
javascript中this指標是動態的,主要是根據當前函式執行背景關系及函式呼叫方式決定的.
- 以函式方法呼叫時
this指標全域或嚴格模式中為undefined - 以方法呼叫時
this是指標當前物件實體的. - 以建構式方式時
this指向當前創建的實作物件 apply、call、lambda運算式可用于系結this指標.
注意:別繞暈了
函式方式呼叫
// 以函式方式呼叫
var x = 2
function test() {
console.log(this.x); // 輸出 2
}
test() // this 為全域物件 windown
以方法呼叫
// 以方法呼叫
var x = "x";
let o = {
x: 2
};
console.log(o.x); // this指標o實體
建構式方式
var x = 1;
function Test() {
this.x = "5x";
}
let b = new Test();
console.log(b.x); // this指標b實體物件
apply與call系結this
apply與call接收的函式引數不同,使用方法都是一樣的.
// apply
var b = "b"
function test() {
console.log(this.b)
}
let o = {
b:22
}
test.apply(o) // 列印出 22 因為把o實體物件系結this指標上了
lambda運算式(箭頭函式)
箭頭函式沒有this指標,箭頭函式里面的this是繼承上層函式this指標.在定義時就系結了的.
// 物件字面量
var x = "x"
var o = {
x: 1,
test: function() {
console.log(this.x); // this指標由呼叫方法決定
}
};
var b = o.test;
b(); // 輸出x, this指向全域
o.test(); // 輸出1 ,this為當前物件實體
物件字面量與箭頭函式
// 物件字面量與箭頭函式
var x = "x";
let o = {
x: 1,
test: () => {
console.log(this.x); // 這里this指標指向的是全域物件
}
};
// 這里this指標指向新創建物件實體
let O = function() {
this.x = 1;
this.test = {
x: 5,
t: () => {
console.log(this.x); // 輸出 1, this繼承于上層函式的this指標
}
};
};
let o = new O();
o.test.t();
實體一
以下示例中 alert 出來的結果分別是?
var color = "藍色";
var test = {
color: "白色",
getColor: function() {
var color = "red"; // 這只是一個區域變數,不是物件成員
alert(this.color);
}
};
var getColor = test.getColor;
getColor(); // 藍色 this 為全域物件
test.getColor(); // 白色 this為當前物件實體
個人博客地址 : https://www.zhuamimi.cn
文章地址 : https://www.zhuamimi.cn/archives/206
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/148159.html
標籤:JavaScript
上一篇:05.JS函式
下一篇:判斷用戶的瀏覽設備
