理解Javascript的闭包

September 28th, 2007 no comment

先来看两段代码,若是你不能完全理解它们的原理,则本文对你还是有一点参考作用的。 首先是我写的一段用来模拟私有成员的代码: function Foobar(parameter) { var privateVariable = “I’m private Variable”; var privateFunction = function() { return “I’m privateFunction and privateVariable is : ” + privateVariable; } this.publicVariable = “I’m public Variable”; this.publicFunction = function() { document.write(“parameter : ” + parameter + “<br />”); document.write(“privateVariable : ” + privateVariable + “<br />”); document.write(“privateFunction : ” [...]

理解Javascript中类的定义

September 28th, 2007 no comment

关于如何在Javascript中定义类,网上可以找到不少的文章。在开始讲之前,还是先来看看定义类的两种基本方式吧: (1) 利用函数构造类型。 function Foo(text, url) { this.text = text; this.url = url; this.render = function() { document.write(‘<a href=”‘ + this.url + ‘”>’ + this.text + ‘</a>’); } } (2) 利用原型prototype。 function Bar(text, url) { this.text = text; this.url = url; } Bar.prototype = { render : function() { document.write(‘<a href=”‘ + this.url + ‘”>’ [...]