bianbian coding life

便便代码人生: 关注技术, 翻译文档, 偶尔动动手

[原] 关于Javascript的this关键字答网友问

Posted by bianbian on 2008-03-25 01:57


本文Tags: , ,

发信人: Net (BBS上没有什么事情是bg不能解决的), 信区: WebDesign
标 题: Re: Javascript问题
发信站: 南京大学小百合站 (Tue Mar 25 01:16:03 2008)

Javascript里的this和其他OO语言不一样
Javascript其实并不适合做OO,其实OO也并不适合Javascript
扯远了。。。。。。
this你就当“执行函数的宿主”理解。因此在一串函数的执行过程中,this不停地在变。

  1. A = {
  2.     member: "OK",
  3.     method: function () {
  4.         alert(this.member);
  5.     }
  6. };
  7. B = A.method;
  8.  
  9. A.method(); //弹出"OK". A是宿主,this.member == A.member
  10. B();        //弹出undefined. window(缺省)是宿主,this.member == window.member

为了解决这个问题,很多框架对此进行了包装。
比如Prototype,用bind,实际是动态生成一个function,把宿主作为动态function的执行者,这样对用户来说,this似乎没有变化。

  1. bind: function() {
  2.     if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
  3.     var __method = this, args = $A(arguments), object = args.shift();
  4.     return function() {
  5.       return __method.apply(object, args.concat($A(arguments)));
  6.     }
  7.   }

实际只要明白this是执行者的指针,一切都可迎刃而解。

标签: , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in JavaScript, Technology | No Comments »

[原] IE模拟鼠标右键双击事件

Posted by bianbian on 2008-03-25 01:10


本文Tags: , , ,

IE实在太垃圾了,再鄙视一次。。。鼠标右键双击居然没有。。。。
只好用onmouseup事件模拟一个(基于Prototype 1.6):

  1. if (Prototype.Browser.IE) {
  2.     mouseCount = 0;
  3.     Event.observe(document, 'mouseup', function(event) {
  4.         if (Event.isRightClick(event)) {
  5.             if (++mouseCount > 1) {
  6.                 mouseCount = 0;
  7.                 var pxy = Event.pointer(event);
  8.                 alert("right mouse double click on: " + pxy.x + ", " + pxy.y);
  9.             } else {
  10.                 setTimeout("mouseCount = 0", 1000);
  11.             }
  12.         }
  13.     });
  14. }
标签: , , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in JavaScript, Technology | 1 Comment »

[原] 也许是prototype框架的bug

Posted by bianbian on 2008-03-08 08:03


本文Tags: , , , ,

不知道怎么给prototype提交bug report,就写在这里吧:
其实我没有测试过,只是看prototype源码的时候,觉得是个bug:
对String的原型(prototype)添加toJSON()函数只是转义了引号,未转义”\”:

  1. if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
  2. return "'" + escapedString.replace(/'/g, '\\\'') + "'";

如果用户在input里输入\\,转成string应该是”\\\\”,如果没有转义,再写回去的时候就丢了一个\
应该在转义引号前先转义\:

  1. .replace(/\\/g, '\\\\').replace(/"/g, '\\"')
标签: , , , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in JavaScript, Technology | No Comments »