an anonymous callback function
is passed in the usual use of setTimeout addEventListener .
such as:
1.
window.setTimeout(function() {
console.log(this)
}, 1000)
2.
var el = document.getElementById("wrapper")
el.addEventListener("click", function() {
console.log(this)
}, false)
in case 1, this points to the caller-> window object of the setTimeout function
, while in case 2, this also points to the caller-> wrapper of the addEventListener function
but I myself am similar to window.setTimeout , which creates an object
var a = {
b: "b in a",
c: function (callback) {
callback()
}
}
//ac
a.c(function() {
//thisa"b in a"thiswindow
console.log(this.b)
})
I thought it would be similar to window.setTimeout el.addEventListener , where this points to the object before . (dot).
then I changed the object a
var a = {
b: "b in a",
c: function (callback) {
callback.bind(this)()
}
}
this is the time when this points to a.
then here comes the problem:
1. Like this use of anonymous function passing parameters , why is it that using my own defined object is not the same as the api provided by the browser? How should the direction of this type of this be better understood ?
2. Is it true that the internal implementation of system api, such as setTimeout and addEventListener helps us to give this bind to the object calling this method, such as callback.bind (window) and addEventListener in setTimeout ? callback.bind (el) ?
are there any great gods who can answer this question? thank you very much.
