`
flyingis
  • 浏览: 294547 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
阅读更多
    译者:Flyingis

    this是JavaScript中功能最强大的关键字之一。不幸的是,如果你不知道它具体怎么工作,你将很难正确使用它。

    下面我来阐述如何在事件处理中来使用this,之后我会附加一些this相关的例子。

    Owner
  
    接下来文章中我们将要讨论的问题是:在函数doSomething()中this所指的是什么?
 
function doSomething() {
  
this.style.color = '#cc0000';
}

    在JavaScript中,this通常指向的是我们正在执行的函数本身(译者注:用owner代表this所指向的内容),或者是,指向该函数所属的对象。当我们在页面中定义了函数doSomething()的时候,它的owner是页面,或者是JavaScript中的window对象(或global对象)。对于一个onclick属性,它为它所属的HTML元素所拥有,this应该指向该HTML元素。

    这种“所有权”就是JavaScript中面向对象的一种方式。在Objects as associative arrays中可以查看一些更多的信息。

this1.gif


    如果我们在没有任何更多准备情况下执行doSomething(),this关键字会指向window,并且该函数试图改变window的style.color。因为window并没有style对象,这个函数将非常不幸的运行失败,并产生JavaScript错误。

    Copying
  
    因此如果我们想充分利用this,我们不得不注意使用this的函数应该被正确的HTML元素所拥有。换句话说,我们应该复制这个函数到我们的onclick属性。Traditional event registration会关心它。

element.onclick = doSomething;

    这个函数被完整复制到onclick属性(现在成为了函数)。因此如果这个event handler被执行,this将指向HTML元素,并且该元素的颜色得以改变。

this2.gif


    这种方法使得我们能够复制这个函数到多个event handler。每次this都将指向正确的HTML元素:

this3.gif


    这样你就可以最大限度使用this。每当执行该函数,this所指向的HTML元素都正确响应事件,这些HTML元素拥有doSomething()的一个拷贝。

    Referring

    然而,如果你使用inline event registration(内联事件注册)

<element onclick="doSomething()">

    你将不能拷贝该函数!反而这种差异是非常关键的。onclick属性并不包含实际的函数,仅仅是一个函数调用。

doSomething();

    因此,它将声明“转到doSomething()并且执行它”。当我们到达doSomething(),this关键字又重新指向了全局的window对象,函数返回错误信息。

this4.gif


    The difference

    如果你想使用this来指向HTML元素响应的事件,你必须确保this关键字被写在onclick属性里。只有在这种情况下它才指向event handler所注册的HTML元素。
 
element.onclick = doSomething;
alert(element.onclick)

    你将得到

function doSomething() {
  
this.style.color = '#cc0000';
}

    正如你所见,this关键字被展现在onclick函数中,因此它指向HTML元素。

    但是如果执行

<element onclick="doSomething()">
alert(element.onclick)

你将得到

function onclick() {
  doSomething()
}

    这仅仅是到doSomething()函数的一个引用。this关键字并没有出现在onclick函数中,因此它不指向HTML元素。

    例子--拷贝

    下面的例子中,this被写入onclick函数里:

element.onclick = doSomething
element.addEventListener('click', doSomething, 
false)
element.onclick 
= function() {this.style.color = '#cc0000';}
<element onclick="this.sytle.color = '#cc0000';">

    例子--引用

    下述情况中,this指向window:

element.onclick = function() {doSomething()}
element.attachEvent('onclick', doSomething)
<element onclick="doSomething()">

    注意attachEvent()的出现。Microsoft event registration model最主要的弊端是attachEvent()创建了一个指向函数的引用,而不是复制它。因此有时不可能知道哪个HTML正在处理该事件。

    组合使用

    当使用内联事件注册时,你可以将this发送到函数以至于可以正常使用:

<element onclick="doSomething(this)">
function doSomething(obj) {
  
//this出现在event handler中并被发送到函数
  //obj指向HTML元素,因此可以这样:
  obj.style.color = '#cc0000';
}

    原文链接:http://www.quirksmode.org/js/this.html
分享到:
评论

相关推荐

    Semantics of Asynchronous JavaScript

    This paper presents the rst comprehensive formalization of the Node.js asynchronous execution model and de nes a high-level notion of async-contexts to formalize fundamental relationships between ...

    JavaScript圣经第六版-英文版

    Updated to include the latest coverage of JavaScript, including howit fits into current Web browsers and applications as well as an exploration of its interaction with XML data in Ajax - This mammoth ...

    编写可维护面向对象的JavaScript代码[翻译]

    console.log(this.name + " is a " + this.title + " with a salary of " + this.salary); }; var employee = new Employee('Alice', 'Developer', '70000'); employee.displayEmployeeInfo(); ``` 2. 使用ES6...

    javascript基础教程 第8版 源代码.

    "陈建* 柳靖 翻译"说明了中文版是由这两位翻译家完成的,确保了中文读者可以理解内容。"只有书中代码部分"意味着这个压缩包中不含文字解释或理论部分,只有实际的编程代码,可能需要配合书籍正文阅读以获取完整理解...

    外文翻译 stus MVC

    This stateless behavior made it difficult for the model to notify the view of changes. On the Web, the browser has to re-query the server to discover modification to the state of the application. ...

    Getting to Know Vue js

    Getting started with a new Single Page Application (SPA) JavaScript framework can be an overwhelming task, but Vue.js makes this daunting task simple and easy to learn, allowing you to start ...

    Node.js Design Patterns Second Edition[July 2016]

    Across this chapter we learn the basic principles of Universal JavaScript by building a simple web application with React, Webpack, and Babel. Chapter 9, Advanced Asynchronous Recipes, takes a ...

    translator-[removed]算盘javascript翻译器

    算盘翻译器-javascript目录去做写这个自述文件。 使所有类名都是绝对的,因此不需要包含。版权 Copyright 2011 Geert MuldersLicensed under the Apache License, Version 2.0 (the "License");you may not use this...

    JS 函数式编程指南

    This is the Simplified Chinese translation of mostly-adequate-guide, thank Professor Franklin Risby for his great work! 关于本书 这本书的主题是函数范式(functional paradigm),我们将使用 JavaScript ...

    Head First HTML5 Programming

    - **Canvas元素**:讲解`&lt;canvas&gt;`标签的基本用法及如何利用JavaScript进行绘图操作,实现动态图像和游戏开发等功能。 - **SVG**:探讨可缩放矢量图形(SVG)的基础知识及其在Web开发中的应用。 ##### 3. Web存储与...

    php外文翻译.docx

    8 Echo "&lt;p&gt;This is a test of PHP.&lt;/p&gt;"; 9?&gt; 10 11 ``` 如我在之前的文中所承认,这只是一个相当无趣的PHP脚本示例。实际上,这个脚本并没有做任何普通HTML页面不能做到的事情。虽然我给出了一个显示当前服务器...

    pig-latin-javascript

    猪拉丁翻译 使用Java的行为驱动开发练习,2015年9月17日 史蒂芬妮·加西亚(Stephany Garcia) 描述 This is a Pig Latin Translator that uses the following rules: * For words that start with a vowel, add "ay...

    Ecma-262 edition 6(ECMAScript® 2015 Language Specification)

    3. 箭头函数(Arrow Functions):提供了一种更简洁的函数书写方式,它自动绑定this值,不会创建自己的this,这对事件处理器和回调函数特别有用。 4. 默认参数(Default Parameters):允许在函数定义中给参数设置...

    吉布斯采样matlab代码-GSW-JS:JavaScript中的GibbsSeaWater(GSW)海洋学工具箱

    this file. index.html - the check javascript functions library. teos.css - A few styles used /js/TEOS10_gsw_oceanographic_toolbox.js - the GSW library except gsw_saar /js/TEOS10_gsw_...

    bing-translate:用于 node.js 的 Bing 翻译模块

    translate ( 'This hotel is located close to the centre of Paris.' , 'en' , 'ro' , function ( err , res ) { console . log ( err , res ) ; } ) ; 语言列表参考 请参阅以获取 BING 支持的语言的

    EhTagTranslator:将e绅士页面TAG换成中文,最全数据库

    This is a project for adult website, and the content of this item may include "sexual expression" and "restricted images" show.View at your own risk. 使用方法 已经迫不及待要来一发了吗?请查看:play_...

    XML轻松学习手册--XML肯定是未来的发展趋势,不论是网页设计师还是网络程序员,都应该及时学习和了解

    例如:当一个title元素"out of stock",将被用红色显示。 4.DOM则为脚本和对象的交流提供一个公共平台,并将结果显示在浏览器窗口。 如果任何一个部分发生错误,都不会得到正确结果。 好了,看到这里,我们已经...

    shadowlog_cht:Shadowlog.com的中文翻译,作为Firefox插件

    shadowlog.com的中文翻译。 安装 对于FireFox 对于Chrome 许可证(GPLv3) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as ...

    深入浅出ES6(Alin标签).pdf

    首先,ES6带来了箭头函数,这是一种更简洁的函数书写方式,它解决了this上下文的坑点,使得函数的书写更加简洁和符合直觉。ES6中的Promise规范,借鉴自其他编程语言,提供了一种更加优雅的处理异步编程的方案。它...

    z-trans:一个简单的翻译器,其工作方式类似于 Symfony 翻译器组件

    这是一个简单的翻译解决方案,其灵感来自 。 它是一个 CommonJS 模块,所以它必须与或类似的东西一起使用,比如 。 例子 // Requiring the module var translator = require ( 'z-trans' ) ; // Adding the ...

Global site tag (gtag.js) - Google Analytics