this
const Person = {
name : `habil`,
}
function panggil(arg1,arg2){
console.log(`nama ${this.name} ${arg1} ${arg2}`)
}
//cara 1
const p = panggil.bind(Person,'arg1', 'arg2')
p() // output : nama habil arg1 arg2
//cara 2 langsung invoke fungsi
panggil.call(Person,'arg1s','arg2s') // output : nama habil args1 args2
//cara 3 langsung panggil fungsinya tapi argumennya dalam array
panggil.apply(Person,['arg1s','arg2s']) // output : nama habil arg1s arg2s
this
akan me-reference secara default ke Window atau Global.this
tidak akan mereference ke objek melainkan ke Window atau Globalcontoh lain :
const Person = {
name : `habil`,
panggilArrow : function() {
setTimeout( () => console.log(this), 100 )
}
panggilFN : function() {
setTimeout ( function () {console.log(this}, 100 )
}
}
Person.panggilArrow() // output : habil seteleh 100 ms
Person.panggilFN() // output : window setelah 100ms
this
pada pada constructor function prototype maka this akan merujuk pada objek instancenya kemudian prototypenya (recursively)function Person(){}
const b = new Person()
Person.prototype.panggil = function(){
return console.log('halo, ' +this.ea)
}
b.ea='ua'
Person.prototype.ea='wakwaw'
b.panggil() // output : halo. ua
/**
jika b.ea='ua' tidak ada maka
output : halo.wakwaw */