欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

Javascript中的this绑定介绍

时间:2021-04-04 10:13:49|栏目:JavaScript代码|点击:
而this的具体值则取决于其调用模式。
* 方法调用模式:this被绑定到该对象。
* 函数调用模式:this被绑定到全局对象,网页的情况下绑定到window
* 构造器调用模式:this被绑定到新生成的对象。
* 事件处理调用模式分两种情况:参照
* this被绑定到全局对象
复制代码 代码如下:

<script type="text/javascript">
function click_handler() {
alert(this); // alerts the window object
}
</script>
...
<button id='thebutton' onclick='click_handler()'>Click me!</button>

* this被绑定到DOM对象
复制代码 代码如下:

<script type="text/javascript">
function click_handler() {
alert(this); // alerts the button DOM node
}
function addhandler() {
document.getElementById('thebutton').onclick = click_handler;
}
window.onload = addhandler;
</script>
...
<button id='thebutton'>Click me!</button>

由于函数调用的上下文的变化导致了this的不确定性。为了更好的明确this上下文,可以使用call和apply两个方法来明确化this绑定的值。
call和apply的区别仅仅在于参数上的区别:call接受任意参数列表,apply接受一个参数数组对象。这也使得apply可以接受arguments作为其第二参数。
复制代码 代码如下:

func.call(obj1,var1,var2,var3)
func.apply(obj1, [var1,var2,var3])
func.apply(obj1, arguments)

但是call和apply方式都是立即执行的,如果需要后来使用的话,就不能满足条件,如下例,其中13行和14行无论是否使用call都无法得到我们需要的值(42)。
复制代码 代码如下:

<script type="text/javascript">
function BigComputer(answer) {
this.the_answer = answer;
this.ask_question = function () {
alert(this.the_answer);
}
}
function addhandler() {
var deep_thought = new BigComputer(42),
the_button = document.getElementById('thebutton');
//the_button.onclick = deep_thought.ask_question;
the_button.onclick = deep_thought.ask_question.call(deep_thought);
}
window.onload = addhandler;
</script>

这个时候就是bind方法大显身手的时候(该方法已经在ECMA-262第五版已经加入),最早出现在Prototype框架中(未确认过)。bind和call,apply一样,也是变更函数执行的上下文,也即函数执行时this的值。不同的在于,它返回一个函数引用以供后续使用,其简单实现如下:
复制代码 代码如下:

Function.prototype.bind = function(object) {
var method = this;
return function() {
method.apply(object, arguments);
}
}

具体实现上利用闭包特性,返回来的函数引用在执行的时候,可以访问创建该函数引用时的method和object两个参数,而不是使用this,this在执行的时候会重新被绑定,而不是原来的method这个值。

上一篇:使用async await 封装 axios的方法

栏    目:JavaScript代码

下一篇:倾力总结40条常见的移动端Web页面问题解决方案

本文标题:Javascript中的this绑定介绍

本文地址:http://www.codeinn.net/misctech/94106.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有