在Javascript中,this這個關鍵字可以說是用的非常多,說他簡單呢也很簡單,說他難呢也很難,有的人開發兩三年了,自己好像也說不清this到底是什么。下面我們來看看:
1、在一般函數方法中使用 this 指代全局對象
function hello(){
this.x = 1;
console.log(this.x)
}
hello();
//此時控制台打印1
2.作為對象方法調用,this 指代上級對象
function hello(){
console.log(this.x)
}
var s = {};
s.x = 1;
o.m = hello;
o.m();
//此時控制台打印1
3.作為構造函數調用,this 指代new 出的對象
function hello(){
this.x = 1;
}
var s = new hello();
console.log(s.x)
//運行結果為1,為了表明這是this不是全局對象,我們對代碼做一些改變
var x = 2;
function hello(){
this.x = 1;
}
var o = new hello();
console.log(x)
4.apply 調用 ,apply方法作用是改變函數的調用對象,此方法的第一個參數為改變后調用這個函數的對象,this指代第一個參數
var x = 0;
function hello(){
console.log(this.x)
}
var h = {};
h.x = 1;
h.m = hello;
h.m.apply(); //輸出為0
h.m.apply(h) //輸出1
以上就是常用的四種方法,大家要是不明白,可以把demo運行一下自己就知道了。
以上部分內容來自網絡,有問題可以在下面評論,技術問題可以在私聊我。
技術QQ群:213365178