簡(jiǎn)單說明 this 4種使用方式:
1窑滞、調(diào)用者使用:
function t(){
this.num = 10;
}
t();
console.log(num) => 10
console.log(window.num) =>10
這樣定義執(zhí)行 t(),this其實(shí)為null,this為null的時(shí)候會(huì)指向到window對(duì)象上
使用 'use strict' 嚴(yán)格模式下梆掸,當(dāng)this 為 null 時(shí) 會(huì)拋出一個(gè)異常服傍!
2尚揣、作為構(gòu)造函數(shù)調(diào)用:
function User(name,age){
this.name = name;
this.age = age;
return "hello"; // 無效的
}
var user = new User('多多','18');
console.log(user);
console.log(typeof(user)) => object
/*
1、 方法(函數(shù)) 被 new 的瞬間,會(huì)得到一個(gè)空對(duì)象 {}
2、方法(函數(shù))的 this 指向該對(duì)象
3匀借、運(yùn)行該方法:
{}.name = name 對(duì)象的name 等于傳過來的 name
{}.color = color
4、最后返回該對(duì)象
5平窘、在構(gòu)造函數(shù) 內(nèi)部 return 是沒用作用的(被忽略)O爬摺!9逅摇J枪怼!
*/
3紫新、函數(shù)通過 call()調(diào)用:可以動(dòng)態(tài)的更改 this 的指向
可以讓當(dāng)前對(duì)象去使用別的對(duì)象的方法
需要的參數(shù)傳遞過去均蜜!
語法:object1.方法 / 函數(shù).call(object2,'參數(shù)1','參數(shù)2',........芒率,'參數(shù)N')
var btn1 = document.querySelector('#btn1');
var btn2 = document.querySelector('#btn2');
function changeBg(){
this.onclick = function (){
this.style.backgroundColor = 'orange';
}.bind(this)
}
t.call(btn1);
t.call(btn2);
4囤耳、函數(shù)/方法 通過 apply()調(diào)用:
也可以動(dòng)態(tài)的更改 this 的指向,和 call()很像偶芍,傳遞參數(shù)的方式不一樣
語法:object1.方法 / 函數(shù).call(object2,['參數(shù)1','參數(shù)2'充择,........,'參數(shù)N'])
如果傳遞的參數(shù)不是 array
=> Uncaught TypeError: CreateListFromArrayLike called on non-object
var Cat = {
name: '小黑貓'
}
var Tigger = {
name: '白虎',
eat: function(obj){
console.log('角色 =>'+this.name + ' 技能 :'+obj);
}
}
Tigger.eat.call(Cat,'別看我小匪蟀,我也會(huì)吃人...')椎麦;
Tigger.eat.apply(Cat,['別看我小,我也會(huì)吃人...'])萄窜;
以上就是this 的簡(jiǎn)單使用铃剔,可以在去深入了解!