Home > Web Front-end > JS Tutorial > body text

Javascript中的this绑定介绍_javascript技巧

WBOY
Release: 2016-05-16 18:01:51
Original
1151 people have browsed it

而this的具体值则取决于其调用模式。
* 方法调用模式:this被绑定到该对象。
* 函数调用模式:this被绑定到全局对象,网页的情况下绑定到window
* 构造器调用模式:this被绑定到新生成的对象。
* 事件处理调用模式分两种情况:参照
* this被绑定到全局对象

复制代码 代码如下:


...


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


...


由于函数调用的上下文的变化导致了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)。
复制代码 代码如下:



这个时候就是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这个值。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!