1. 关于This
执向问题,有三个要点:
-
this
的指向跟函数本身没有关系,取决于函数被谁调用。 - 基于函数被调用,
this
的指向是动态的。 - 你可以通过调用.call() .bind() .apply()来改变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()
的区别
call
与apply
功能类似,区别在于apply
的传参需要以数组的形式。
bind
与call
的区别在于,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
- 初始全局执行上下文
在初始全局执行上下文中评估代码时,ThisBinding被设置为全局对象“window” - 在对象方法中使用时
在对象方法中使用此关键字时,它将绑定到“立即”封闭对象。 - 调用无上下文功能时
当你使用这个在没有任何上下文的情况下调用的函数(即不在任何对象上)时,它被绑定到全局对象(浏览器中的窗口)(即使函数是在对象内部定义的)。 - 在构造函数中使用时
当函数被用作构造函数时(即使用new关键字调用它时),此内部函数体指向正在构建的新对象。 - 在原型链上定义的函数内使用时
如果该方法位于对象的原型链上,则此方法内部引用方法被调用的对象,就好像方法在对象上定义一样。
网友评论