this的含義
this表示的是系結的物件,通常在函式中使用,
不同的代碼形式下,系結的物件代表不同的東西,
下面看一下常見的幾種代碼形式:
一、獨立的函式
function foo() {
console.log(this); // this就是window物件
console.log(this.innerWidth); // 列印客戶端視窗寬度
}
foo();
二、物件的方法
var obj = {
x: 10,
y: 20,
point: function() {
console.log(this); // this是方法所屬的obj物件本身
console.log(this.x, this.y); // 列印出obj物件的屬性
}
}
obj.point();
三、事件處理程式
document.addEventListener('click', function() {
console.log(this); // this是觸發事件的那個物件
this.body.innerHTML += '被點擊了!';
})
四、建構式
function Foo() {
console.log(this); // this是瀏覽器自動幫我們新創建的空白物件
this.x = 1;
this.y = 2;
}
// new Foo(); // Foo{}
var f = new Foo();
console.log(f);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/108292.html
標籤:JavaScript
