this points to the problem.
this points to
ღ During function precompilation, this points to window.
Define a this in the function,
function test() {
console.log(this);
}
test();
console output
ღ In the global scope, this points to window.
Output this directly on the console
ღ call and apply can change the point of this at runtime.
See the blog call and apply section for details
ღ Whoever calls this, this points to.
<script type="text/javascript">
var test = {
a : function (){
console.log(this.name);
},
name : '墨小白'
}
test.a();
</script>
test calls this, so it points to test, and finally outputs Mo Xiaobai.
this exercise
<script type="text/javascript">
var name = '222';
var a = {
name : '111',
say : function () {
console.log(this.name);
}
}
var fun = a.say;
//a.say把函数引用赋值给fun
fun();
//fun在全局内内执行
//function () {console.log(this.name)}
//此时的this.name指向的时window,所以输出 '222'
a.say();
//对象a调用了this,所以指向对象a,输出'111'
var b = {
name : '333',
say : function(fun) {
fun();
}
}
b.say(a.say);
//...看解析
b.say = a.say;
b.say();
//b对象say属性值变成函数引用function () {console.log(this.name)}
//然后使用b执行,此时是b调用this,所以输出'333'
</script>
b.say(a.say) is executed by passing parameters, and the passed parameters are function references
function () {
console.log(this.name);
}
After simulating parameter transfer
var b = {
name : '333',
say : function(fun) {
(function () {
console.log(this.name);
})();
}
}
Because it is used to pass parameters for execution, it should be this immediately executed function after passing parameters.
The executed this is not called by anyone, so it points to the global and outputs '222'