[翻译]PPK 谈 JavaScript 的 this 关键字
原文:JavaScript - The this keyword
在 JavaScript 中 this 是最强的关键字之一。这篇贴文就是要告诉你如何用好 this。
下面先讲如何在event handling
(事件处理)中用它,再接着是讲 this 的其他用法。
所有者(Owner)
先来看看函数 doSomething() 里的 this 究竟指向(refer to)了什么?
function doSomething() {
this.style.color = '#cc0000';
}
JavaScript的 this 总是指向正执行的函数的所有者。或者是说,它是指向函数这个对象的一种手法。
在页面中定义了
doSomething() 函数时,它的所有者是页面。确切的说是指 JavaScript 的 window 对象(全局对象)。
而
onclick 属性归属 HTML 元素所有。
这种归属谁所有的权利是 JavaScript 的 OO(面向对象)特性的结果。在 把对象作关联数组
页面中有更多信息。
------------ window --------------------------------------
| / \ |
| | |
| this |
| ---------------- | |
| | HTML 元素 | <-- this ----------------- |
| ---------------- | | doSomething() | |
| | | ----------------- |
| -------------------- |
| | onclick 属性 | |
| -------------------- |
| |
----------------------------------------------------------
这里在 doSomething() 执行时,关键字 this 指向 window(窗口) ,该函数将会改动 window 的 style.color。
而 window 没有 style 这个对象,所以该函数会引发 JavaScript 的错误。
拷贝(copying)
因此,想要用好 this 就请继续往下看。像前面的例子在函数中使用的这种情况,this 指向它归属谁所有的那个 HTML 元素。
也就是说,有个函数拷贝指向 onclick 属性。 我们来看看在传统事件注册
中的情况。
element.onclick = doSomething;
函数是它整个的拷贝,指向 onclick 属性(现在变成了方法)。因此,事件处理被执行时,this 指向 HTML 元素并将改动 color。
----------
相关文档:
Return a formatted string
function sprintf ( ) {
// Return a formatted string
//
// version: 909.322
// discuss at: http://phpjs.org/functions/sprintf // + original by: Ash Searle (http://hexmen.com/blog/)
// + namespaced by: Michael White (http://getsprink.com)
......
按钮式:
<INPUT name="pclog" type="button" value="GO" onClick="location.href='url'">
直接跳转式:
<script>window.location.href='url';</script>
<SCRIPT LANGUAGE="javascript">
<!--
window.open
('page.html' ......
一、概述
考虑Html本身不带定时刷新页面的控件,且不考虑使用第三方控件;因此考虑使用Javascript中的setTimeout+xmlhttp来实现定时更新页面中部分内容,此实现在IE6.0及以上版本测试通过,其他浏览器暂时未测试过。
二、功能及特点
1、Javascript通过Microsoft的MSXML对象,动态获取后台数据库数据;
&n ......
var myDate = new Date();
myDate.getYear(); //获取当前年份(2位)
myDate.getFullYear(); //获取完整的年份(4位,1970-????)
myDate.getMonth(); //获取当前月份(0-11,0代表1 ......