JavaScript this的指向问题

2018-06-02  本文已影响11人  PaulLuv

原文参考toddmotto

1. 关于This执向问题,有三个要点:

  • The this keyword’s value has nothing to do with the function itself, how the function is called determines thethis value.
  • It can be dynamic, based on how the function is called.
  • You can change the this context through .call(), .apply() and .bind()

2. call()apply()bind()的区别

callapply 功能类似,区别在于apply的传参需要以数组的形式。
bindcall的区别在于,bind只是设置值不会触发函数(Using .bind() will not invoke the function, it just “sets it up”)。
看一个实例:

 var xw = {
    name : "小王",
    gender : "男",
    age : 24,
    say : function(school,grade) {
            alert(this.name + " , " + this.gender + " ,今年" + this.age + " ,在" + school + "上" + grade);                                
    }
}
var xh = {
    name : "小红",
    gender : "女",
    age : 18
}
xw.say.call(xh,"实验小学","六年级"); 
xw.say.apply(xh,["实验中学","初一年级"]);
xw.say.bind(xh,"实验高学","高一年级")();
xw.say.bind(xh)("实验大学","大一年级");

3. this的官方标准定义

evaluates to the value of the ThisBinding of the current execution context;

评估为当前执行的上下文的ThisBinding的值

ThisBinding is something that the JavaScript interpretermaintains as it evaluates JavaScript code, like a specialCPU register which holds a reference to an object. Theinterpreter updates the ThisBinding whenever establishingan execution context in one of only three different cases:

ThisBinding是JavaScript解释器在评估JavaScript代码时维护的东西就像一个特殊的CPU寄存器,它持有对象的引用。

4. this指向的几种示例

this与HTML元素的示例

element.onclick = doSomething;
// doSomething() 内的this 为 element
<element onclick="doSomething()">
// doSomething() 内的this 为 window
上一篇 下一篇

猜你喜欢

热点阅读