Javascript 面向对象编程
fmms
13年前
<p> Javascript 是一个类C的语言,他的面向对象的东西相对于C++/Java 比较奇怪,但是其的确相当的强大,在 Todd 同学的“<a title="对象的消息模型" href="/misc/goto?guid=4959500522490830078" rel="bookmark" target="_blank">对象的消息模型</a>”一文中我们已经可以看到一些端倪了。这两天有个前同事总在问我 Javascript 面向对象的东西,所以,索性写篇文章让他看去吧,这里这篇文章主要想从一个整体的角度来说明一下 Javascript 的面向对象的编程。(<strong>成文比较仓促,应该有不准确或是有误的地方,请大家批评指正</strong>)</p> <p> 另,这篇文章主要基于 <a href="/misc/goto?guid=4958878706709729781" target="_blank">ECMAScript 5</a>, 旨在介绍新技术。关于兼容性的东西,请看最后一节。</p> <p> <strong>初探</strong></p> <p> 我们知道 Javascript 中的变量定义基本如下:</p> <div> <pre><span style="color:#0000ff;">var</span> name = 'Chen Hao';<span style="color:#0000ff;">var</span> email = 'haoel (@) hotmail.com';<span style="color:#0000ff;">var</span> website = 'http://coolshell.cn';</pre> </div> <p> 如果要用对象来写的话,就是下面这个样子:</p> <div> <pre><span style="color:#0000ff;">var</span> chenhao = { name :'Chen Hao', email : 'haoel (@) hotmail.com', website : 'http://coolshell.cn' };</pre> </div> <p> 于是,我就可以这样访问:</p> <div> <pre><span>//</span><span style="color:#008000;">以成员的方式</span><span style="color:#008000;"> </span>chenhao.name; chenhao.email; chenhao.website;<span>//</span><span style="color:#008000;">以 hash map 的方式</span><span style="color:#008000;"> </span>chenhao["name"]; chenhao["email"]; chenhao["website"];</pre> </div> <p> 关于函数,我们知道 Javascript 的函数是这样的:</p> <div> <pre><span style="color:#0000ff;">var</span> doSomething = <span style="color:#0000ff;">function</span>(){ alert ('Hello World.'); }; </pre> </div> <p> 于是,我们可以这么干:</p> <div> <pre><span style="color:#0000ff;">var</span> sayHello = <span style="color:#0000ff;">function</span>(){ <span style="color:#0000ff;">var</span> hello = "Hello, I'm "+ <span style="color:#0000ff;">this</span>.name + ", my email is: " + <span style="color:#0000ff;">this</span>.email + ", my website is: " + <span style="color:#0000ff;">this</span>.website; alert (hello); };<span style="color:#008000;">//</span><span style="color:#008000;">直接赋值,这里很像C/C++的函数指针</span><span style="color:#008000;"> </span>chenhao.Hello = sayHello; chenhao.Hello ();</pre> </div> <p> 相信这些东西都比较简单,大家都明白了。 可以看到 javascript 对象函数是直接声明,直接赋值,直接就用了。runtime 的动态语言。</p> <p> 还有一种比较规范的写法是:</p> <div> <pre><span style="color:#008000;">//</span><span style="color:#008000;">我们可以看到, 其用 function 来做 class。</span><span style="color:#008000;"> </span><span style="color:#0000ff;">var</span> Person = <span style="color:#0000ff;">function</span>(name, email, website){ <span style="color:#0000ff;">this</span>.name = name; <span style="color:#0000ff;">this</span>.email = email; <span style="color:#0000ff;">this</span>.website = website; <span style="color:#0000ff;">this</span>.sayHello = <span style="color:#0000ff;">function</span>(){ <span style="color:#0000ff;">var</span> hello = "Hello, I'm "+ <span style="color:#0000ff;">this</span>.name + ", \n" + "my email is: " + <span style="color:#0000ff;">this</span>.email + ", \n" + "my website is: " + <span style="color:#0000ff;">this</span>.website; alert (hello); }; };<span style="color:#0000ff;">var</span> chenhao = <span style="color:#0000ff;">new</span> Person ("Chen Hao", "haoel@hotmail.com", "http://coolshell.cn"); chenhao.sayHello ();</pre> </div> <p> 顺便说一下,要删除对象的属性,很简单:</p> <div> <pre><span style="color:#0000ff;">delete</span> chenhao['email']</pre> </div> <p> 上面的这些例子,我们可以看到这样几点:</p> <ol> <li>Javascript 的数据和成员封装很简单。没有类完全是对象操作。纯动态!</li> <li>Javascript function 中的 this 指针很关键,如果没有的话,那就是局部变量或局部函数。</li> <li>Javascript 对象成员函数可以在使用时临时声明,并把一个全局函数直接赋过去就好了。</li> <li>Javascript 的成员函数可以在实例上进行修改,也就是说不同实例相同函数名的行为不一定一样。</li> </ol> <p> <strong>属性配置 – Object.defineProperty</strong></p> <p> 先看下面的代码:</p> <div> <pre><span>//</span><span style="color:#008000;">创建对象</span><span style="color:#008000;"> </span><span style="color:#0000ff;">var</span> chenhao = Object.create (<span style="color:#0000ff;">null</span>);<span style="color:#008000;">//</span><span style="color:#008000;">设置一个属性</span><span style="color:#008000;"> </span>Object.defineProperty ( chenhao, 'name', { value: 'Chen Hao', writable: <span style="color:#0000ff;">true</span>, configurable: <span style="color:#0000ff;">true</span>, enumerable: <span style="color:#0000ff;">true</span> });<span style="color:#008000;">//</span><span style="color:#008000;">设置多个属性</span><span style="color:#008000;"> </span>Object.defineProperties ( chenhao, { 'email' : { value: 'haoel@hotmail.com', writable: <span style="color:#0000ff;">true</span>, configurable: <span style="color:#0000ff;">true</span>, enumerable: <span style="color:#0000ff;">true</span> }, 'website': { value: 'http://coolshell.cn', writable: <span style="color:#0000ff;">true</span>, configurable: <span style="color:#0000ff;">true</span>, enumerable: <span style="color:#0000ff;">true</span> } } );</pre> </div> <p> 下面就说说这些属性配置是什么意思。</p> <ul> <li>writable:这个属性的值是否可以改。</li> <li>configurable:这个属性的配置是否可以改。</li> <li>enumerable:这个属性是否能在 for…in 循环中遍历出来或在 Object.keys 中列举出来。</li> <li>value:属性值。</li> <li>get ()/set (_value):get 和 set 访问器。</li> </ul> <p> <strong>Get/Set 访问器</strong></p> <p> 关于 get/set 访问器,它的意思就是用 get/set 来取代 value(其不能和 value 一起使用),示例如下:</p> <div> <pre><span style="color:#0000ff;">var</span> age = 0; Object.defineProperty ( chenhao, 'age', { get: <span style="color:#0000ff;">function</span>() {<span style="color:#0000ff;">return</span> age+1;}, set: <span style="color:#0000ff;">function</span>(value) {age = value;} enumerable : <span style="color:#0000ff;">true</span>, configurable : <span style="color:#0000ff;">true</span> } ); chenhao.age = 100; <span style="color:#008000;">//</span><span style="color:#008000;">调用 set</span><span style="color:#008000;"> </span>alert (chenhao.age); <span style="color:#008000;">//</span><span style="color:#008000;">调用 get 输出 101(get 中 +1 了);</span></pre> </div> <p> 我们再看一个更为实用的例子——利用已有的属性(age)通过 get 和 set 构造新的属性(birth_year):</p> <div> <pre>Object.defineProperty ( chenhao, 'birth_year', { get: <span style="color:#0000ff;">function</span>() { <span style="color:#0000ff;">var</span> d = <span style="color:#0000ff;">new</span> Date (); <span style="color:#0000ff;">var</span> y = d.getFullYear (); <span style="color:#0000ff;">return</span> ( y - <span style="color:#0000ff;">this</span>.age ); }, set: <span style="color:#0000ff;">function</span>(year) { <span style="color:#0000ff;">var</span> d = <span style="color:#0000ff;">new</span> Date (); <span style="color:#0000ff;">var</span> y = d.getFullYear (); <span style="color:#0000ff;">this</span>.age = y - year; } } ); alert (chenhao.birth_year); chenhao.birth_year = 2000; alert (chenhao.age);</pre> </div> <p> 这样做好像有点麻烦,你说,我为什么不写成下面这个样子:</p> <div> <pre><span style="color:#0000ff;">var</span> chenhao = { name: "Chen Hao", email: "haoel@hotmail.com", website: "http://coolshell.cn", age: 100, get birth_year () { <span style="color:#0000ff;">var</span> d = <span style="color:#0000ff;">new</span> Date (); <span style="color:#0000ff;">var</span> y = d.getFullYear (); <span style="color:#0000ff;">return</span> ( y - <span style="color:#0000ff;">this</span>.age ); }, set birth_year (year) { <span style="color:#0000ff;">var</span> d = <span style="color:#0000ff;">new</span> Date (); <span style="color:#0000ff;">var</span> y = d.getFullYear (); <span style="color:#0000ff;">this</span>.age = y - year; } }; alert (chenhao.birth_year); chenhao.birth_year = 2000; alert (chenhao.age);</pre> </div> <p> 是的,你的确可以这样的,不过通过 defineProperty ()你可以干这些事:</p> <p> 1)设置如 writable,configurable,enumerable 等这类的属性配置。</p> <p> 2)动态地为一个对象加属性。比如:一些 HTML 的 DOM 对像。</p> <p> <strong>查看对象属性配置</strong></p> <p> 如果查看并管理对象的这些配置,下面有个程序可以输出对象的属性和配置等东西:</p> <div> <pre><span style="color:#008000;">//</span><span style="color:#008000;">列出对象的属性.</span><span style="color:#008000;"> </span><span style="color:#0000ff;">function</span> listProperties (obj) { <span style="color:#0000ff;">var</span> newLine = "<br />"; <span style="color:#0000ff;">var</span> names = Object.getOwnPropertyNames (obj); <span style="color:#0000ff;">for</span> (<span style="color:#0000ff;">var</span> i = 0; i < names.length; i++) { <span style="color:#0000ff;">var</span> prop = names[i]; document.write (prop + newLine); <span style="color:#008000;">//</span><span style="color:#008000;"> 列出对象的属性配置(descriptor)动用 getOwnPropertyDescriptor 函数。</span><span style="color:#008000;"> </span> <span style="color:#0000ff;">var</span> descriptor = Object.getOwnPropertyDescriptor (obj, prop); <span style="color:#0000ff;">for</span> (<span style="color:#0000ff;">var</span> attr <span style="color:#0000ff;">in</span> descriptor) { document.write ("..." + attr + ': ' + descriptor[attr]); document.write (newLine); } document.write (newLine); } } listProperties (chenhao);</pre> </div> <p> <strong>call,apply, bind 和 this</strong></p> <p> 关于 Javascript 的 this 指针,和C++/Java 很类似。 我们来看个示例:(这个示例很简单了,我就不多说了)</p> <div> <pre><span style="color:#0000ff;">function</span> print (text){ document.write (<span style="color:#0000ff;">this</span>.value + ' - ' + text+ '<br>'); }<span style="color:#0000ff;">var</span> a = {value: 10, print : print};<span style="color:#0000ff;">var</span> b = {value: 20, print : print}; print ('hello');<span style="color:#008000;">//</span><span style="color:#008000;"> this => global, output "undefined - hello"</span><span style="color:#008000;"> </span>a.print ('a');<span style="color:#008000;">//</span><span style="color:#008000;"> this => a, output "10 - a"</span><span style="color:#008000;"> </span>b.print ('b'); <span style="color:#008000;">//</span><span style="color:#008000;"> this => b, output "20 - b"</span><span style="color:#008000;"> </span>a['print']('a'); <span style="color:#008000;">//</span><span style="color:#008000;"> this => a, output "10 - a"</span></pre> </div> <p> 我们再来看看 call 和 apply,这两个函数的差别就是参数的样子不一样,另一个就是性能不一样,apply 的性能要差很多。(关于性能,可到 <a href="/misc/goto?guid=4958344666938267688" target="_blank">JSPerf</a> 上去跑跑看看)</p> <div> <pre>print.call (a, 'a'); <span style="color:#008000;">//</span><span style="color:#008000;"> this => a, output "10 - a"</span><span style="color:#008000;"> </span>print.call (b, 'b'); <span style="color:#008000;">//</span><span style="color:#008000;"> this => b, output "20 - b"</span><span style="color:#008000;"> </span>print.apply (a, ['a']); <span style="color:#008000;">//</span><span style="color:#008000;"> this => a, output "10 - a"</span><span style="color:#008000;"> </span>print.apply (b, ['b']); <span style="color:#008000;">//</span><span style="color:#008000;"> this => b, output "20 - b"</span></pre> </div> <p> 但是在 bind 后,this 指针,可能会有不一样,但是因为 Javascript 是动态的。如下面的示例</p> <div> <pre><span style="color:#0000ff;">var</span> p = print.bind (a); p('a'); <span style="color:#008000;">//</span><span style="color:#008000;"> this => a, output "10 - a"</span><span style="color:#008000;"> </span>p.call (b, 'b'); <span style="color:#008000;">//</span><span style="color:#008000;"> this => a, output "10 - b"</span><span style="color:#008000;"> </span>p.apply (b, ['b']); <span style="color:#008000;">//</span><span style="color:#008000;"> this => a, output "10 - b"</span></pre> </div> <p> <strong>继承和重载</strong></p> <p> 通过上面的那些示例,我们可以通过 Object.create ()来实际继承,请看下面的代码,Student 继承于 Object。</p> <div> <pre><span style="color:#0000ff;">var</span> Person = Object.create (<span style="color:#0000ff;">null</span>); Object.defineProperties ( Person, { 'name' : { value: 'Chen Hao'}, 'email' : { value : 'haoel@hotmail.com'}, 'website': { value: 'http://coolshell.cn'} } ); Person.sayHello = <span style="color:#0000ff;">function</span> () { <span style="color:#0000ff;">var</span> hello = "<p>Hello, I am "+ <span style="color:#0000ff;">this</span>.name + ", <br>" + "my email is: " + <span style="color:#0000ff;">this</span>.email + ", <br>" + "my website is: " + <span style="color:#0000ff;">this</span>.website; document.write (hello + "<br>"); }<span style="color:#0000ff;">var</span> Student = Object.create (Person); Student.no = "1234567"; <span style="color:#008000;">//</span><span style="color:#008000;">学号</span><span style="color:#008000;"> </span>Student.dept = "Computer Science"; <span style="color:#008000;">//</span><span style="color:#008000;">系</span><span style="color:#008000;"> </span><span style="color:#008000;">//</span><span style="color:#008000;">使用 Person 的属性</span><span style="color:#008000;"> </span>document.write (Student.name + ' ' + Student.email + ' ' + Student.website +'<br>');<span style="color:#008000;">//</span><span style="color:#008000;">使用 Person 的方法</span><span style="color:#008000;"> </span>Student.sayHello ();<span style="color:#008000;">//</span><span style="color:#008000;">重载 SayHello 方法</span><span style="color:#008000;"> </span>Student.sayHello = <span style="color:#0000ff;">function</span> (person) { <span style="color:#0000ff;">var</span> hello = "<p>Hello, I am "+ <span style="color:#0000ff;">this</span>.name + ", <br>" + "my email is: " + <span style="color:#0000ff;">this</span>.email + ", <br>" + "my website is: " + <span style="color:#0000ff;">this</span>.website + ", <br>" + "my student no is: " + <span style="color:#0000ff;">this</span>. no + ", <br>" + "my departent is: " + <span style="color:#0000ff;">this</span>. dept; document.write (hello + '<br>'); }<span style="color:#008000;">//</span><span style="color:#008000;">再次调用</span><span style="color:#008000;"> </span>Student.sayHello ();<span style="color:#008000;">//</span><span style="color:#008000;">查看 Student 的属性(只有 no 、 dept 和重载了的 sayHello)</span><span style="color:#008000;"> </span>document.write ('<p>' + Object.keys (Student) + '<br>');</pre> </div> <p> 通用上面这个示例,我们可以看到,Person 里的属性并没有被真正复制到了 Student 中来,但是我们可以去存取。这是因为 Javascript 用委托实现了这一机制。其实,这就是 Prototype,Person 是 Student 的 Prototype。</p> <p> 当我们的代码需要一个属性的时候,Javascript 的引擎会先看当前的这个对象中是否有这个属性,如果没有的话,就会查找他的 Prototype 对象是否有这个属性,一直继续下去,直到找到或是直到没有 Prototype 对象。</p> <p> 为了证明这个事,我们可以使用 Object.getPrototypeOf ()来检验一下:</p> <div> <pre>Student.name = 'aaa';<span style="color:#008000;">//</span><span style="color:#008000;">输出 aaa</span><span style="color:#008000;"> </span>document.write ('<p>' + Student.name + '</p>');<span style="color:#008000;">//</span><span style="color:#008000;">输出 Chen Hao</span><span style="color:#008000;"> </span>document.write ('<p>' +Object.getPrototypeOf (Student) .name + '</p>');</pre> </div> <p> 于是,你还可以在子对象的函数里调用父对象的函数,就好像 C++ 里的 Base::func () 一样。于是,我们重载 hello 的方法就可以使用父类的代码了,如下所示:</p> <div> <pre><span style="color:#008000;">//</span><span style="color:#008000;">新版的重载 SayHello 方法</span><span style="color:#008000;"> </span>Student.sayHello = <span style="color:#0000ff;">function</span> (person) { Object.getPrototypeOf (<span style="color:#0000ff;">this</span>) .sayHello.call (<span style="color:#0000ff;">this</span>); <span style="color:#0000ff;">var</span> hello = "my student no is: " + <span style="color:#0000ff;">this</span>. no + ", <br>" + "my departent is: " + <span style="color:#0000ff;">this</span>. dept; document.write (hello + '<br>'); }</pre> </div> <p> 这个很强大吧。</p> <p> <strong>组合</strong></p> <p> 上面的那个东西还不能满足我们的要求,我们可能希望这些对象能真正的组合起来。为什么要组合?因为我们都知道是这是 OO 设计的最重要的东西。不过,这对于 Javascript 来并没有支持得特别好,不好我们依然可以搞定个事。</p> <p> 首先,我们需要定义一个 Composition 的函数:(target 是作用于是对象,source 是源对象),下面这个代码还是很简单的,就是把 source 里的属性一个一个拿出来然后定义到 target 中。</p> <div> <pre><span style="color:#0000ff;">function</span> Composition (target, source) { <span style="color:#0000ff;">var</span> desc = Object.getOwnPropertyDescriptor; <span style="color:#0000ff;">var</span> prop = Object.getOwnPropertyNames; <span style="color:#0000ff;">var</span> def_prop = Object.defineProperty; prop (source) .forEach ( <span style="color:#0000ff;">function</span>(key) { def_prop (target, key, desc (source, key)) } ) <span style="color:#0000ff;">return</span> target; }</pre> </div> <p> 有了这个函数以后,我们就可以这来玩了:</p> <div> <pre><span style="color:#008000;">//</span><span style="color:#008000;">艺术家</span><span style="color:#008000;"> </span><span style="color:#0000ff;">var</span> Artist = Object.create (<span style="color:#0000ff;">null</span>); Artist.sing = <span style="color:#0000ff;">function</span>() { <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">this</span>.name + ' starts singing...'; } Artist.paint = <span style="color:#0000ff;">function</span>() { <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">this</span>.name + ' starts painting...'; }<span style="color:#008000;">//</span><span style="color:#008000;">运动员</span><span style="color:#008000;"> </span><span style="color:#0000ff;">var</span> Sporter = Object.create (<span style="color:#0000ff;">null</span>); Sporter.run = <span style="color:#0000ff;">function</span>() { <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">this</span>.name + ' starts running...'; } Sporter.swim = <span style="color:#0000ff;">function</span>() { <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">this</span>.name + ' starts swimming...'; } Composition (Person, Artist); document.write (Person.sing () + '<br>'); document.write (Person.paint () + '<br>'); Composition (Person, Sporter); document.write (Person.run () + '<br>'); document.write (Person.swim () + '<br>');<span style="color:#008000;">//</span><span style="color:#008000;">看看 Person 中有什么?(输出:sayHello,sing,paint,swim,run)</span><span style="color:#008000;"> </span>document.write ('<p>' + Object.keys (Person) + '<br>');</pre> </div> <p> <strong>Prototype 和继承</strong></p> <p> 我们先来说说 Prototype。我们先看下面的例程,这个例程不需要解释吧,很像C语言里的函数指针,在C语言里这样的东西见得多了。</p> <div> <pre><span style="color:#0000ff;">var</span> plus = <span style="color:#0000ff;">function</span>(x,y){ document.write ( x + ' + ' + y + ' = ' + (x+y) + '<br>'); <span style="color:#0000ff;">return</span> x + y; };<span style="color:#0000ff;">var</span> minus = <span style="color:#0000ff;">function</span>(x,y){ document.write (x + ' - ' + y + ' = ' + (x-y) + '<br>'); <span style="color:#0000ff;">return</span> x - y; };<span style="color:#0000ff;">var</span> operations = { '+': plus, '-': minus };<span style="color:#0000ff;">var</span> calculate = <span style="color:#0000ff;">function</span>(x, y, operation){ <span style="color:#0000ff;">return</span> operations[operation](x, y); }; calculate (12, 4, '+'); calculate (24, 3, '-');</pre> </div> <p> 那么,我们能不能把这些东西封装起来呢,我们需要使用 prototype。看下面的示例:</p> <div> <pre><span style="color:#0000ff;">var</span> Cal = <span style="color:#0000ff;">function</span>(x, y){ <span style="color:#0000ff;">this</span>.x = x; <span style="color:#0000ff;">this</span>.y = y; } Cal.prototype.operations = { '+': <span style="color:#0000ff;">function</span>(x, y) { <span style="color:#0000ff;">return</span> x+y;}, '-': <span style="color:#0000ff;">function</span>(x, y) { <span style="color:#0000ff;">return</span> x-y;} }; Cal.prototype.calculate = <span style="color:#0000ff;">function</span>(operation){ <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">this</span>.operations[operation](<span style="color:#0000ff;">this</span>.x, <span style="color:#0000ff;">this</span>.y); };<span style="color:#0000ff;">var</span> c = <span style="color:#0000ff;">new</span> Cal (4, 5); Cal.calculate ('+'); Cal.calculate ('-');</pre> </div> <p> 这就是 prototype 的用法,prototype 是 javascript 这个语言中最重要的内容。网上有太多的文章介始这个东西了。说白了,prototype 就是对一对象进行扩展,其特点在于通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的(当然,这里没有真正的复制,实际只是委托)。上面的这个例子中,我们扩展了实例 Cal,让其有了一个 operations 的属性和一个 calculate 的方法。</p> <p> 这样,我们可以通过这一特性来实现继承。还记得我们最最前面的那个 Person 吧, 下面的示例是创建一个 Student 来继承 Person。</p> <div> <pre><span style="color:#0000ff;">function</span> Person (name, email, website){ <span style="color:#0000ff;">this</span>.name = name; <span style="color:#0000ff;">this</span>.email = email; <span style="color:#0000ff;">this</span>.website = website; }; Person.prototype.sayHello = <span style="color:#0000ff;">function</span>(){ <span style="color:#0000ff;">var</span> hello = "Hello, I am "+ <span style="color:#0000ff;">this</span>.name + ", <br>" + "my email is: " + <span style="color:#0000ff;">this</span>.email + ", <br>" + "my website is: " + <span style="color:#0000ff;">this</span>.website; <span style="color:#0000ff;">return</span> hello; };<span style="color:#0000ff;">function</span> Student (name, email, website, no, dept){ <span style="color:#0000ff;">var</span> proto = Object.getPrototypeOf; proto (Student.prototype) .constructor.call (<span style="color:#0000ff;">this</span>, name, email, website); <span style="color:#0000ff;">this</span>.no = no; <span style="color:#0000ff;">this</span>.dept = dept; }<span style="color:#008000;">//</span><span style="color:#008000;"> 继承 prototype</span><span style="color:#008000;"> </span>Student.prototype = Object.create (Person.prototype);<span style="color:#008000;">//</span><span style="color:#008000;">重置构造函数</span><span style="color:#008000;"> </span>Student.prototype.constructor = Student;<span style="color:#008000;">//</span><span style="color:#008000;">重载 sayHello ()</span><span style="color:#008000;"> </span>Student.prototype.sayHello = <span style="color:#0000ff;">function</span>(){ <span style="color:#0000ff;">var</span> proto = Object.getPrototypeOf; <span style="color:#0000ff;">var</span> hello = proto (Student.prototype) .sayHello.call (<span style="color:#0000ff;">this</span>) + '<br>'; hello += "my student no is: " + <span style="color:#0000ff;">this</span>. no + ", <br>" + "my departent is: " + <span style="color:#0000ff;">this</span>. dept; <span style="color:#0000ff;">return</span> hello; };<span style="color:#0000ff;">var</span> me = <span style="color:#0000ff;">new</span> Student ( "Chen Hao", "haoel@hotmail.com", "http://coolshell.cn", "12345678", "Computer Science" ); document.write (me.sayHello ());</pre> </div> <p> <strong>兼容性</strong></p> <p> 上面的这些代码并不一定能在所有的浏览器下都能运行,因为上面这些代码遵循 ECMAScript 5 的规范,关于 ECMAScript 5 的浏览器兼容列表,你可以看这里“<a href="/misc/goto?guid=4958336441557726449" target="_blank">ES5浏览器兼容表</a>”。</p> <p> 本文中的所有代码都在 Chrome 最新版中测试过了。</p> <p> 下面是一些函数,可以用在不兼容 ES5 的浏览器中:</p> <p> <strong>Object.create ()函数</strong></p> <div> <pre><span style="color:#0000ff;">function</span> clone (proto) { <span style="color:#0000ff;">function</span> Dummy () { } Dummy.prototype = proto; Dummy.prototype.constructor = Dummy; <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> Dummy (); <span style="color:#008000;">//</span><span style="color:#008000;">等价于 Object.create (Person);</span><span style="color:#008000;"> </span>}<span style="color:#0000ff;">var</span> me = clone (Person);</pre> </div> <p> <strong>defineProperty ()函数</strong></p> <div> <pre><span style="color:#0000ff;">function</span> defineProperty (target, key, descriptor) { <span style="color:#0000ff;">if</span> (descriptor.value){ target[key] = descriptor.value; }<span style="color:#0000ff;">else</span> { descriptor.get && target.__defineGetter__(key, descriptor.get); descriptor.set && target.__defineSetter__(key, descriptor.set); } <span style="color:#0000ff;">return</span> target }</pre> </div> <p> <strong>keys ()函数</strong></p> <div> <pre><span style="color:#0000ff;">function</span> keys (object) { <span style="color:#0000ff;">var</span> result, key result = []; <span style="color:#0000ff;">for</span> (key <span style="color:#0000ff;">in</span> object){ <span style="color:#0000ff;">if</span> (object.hasOwnProperty (key)) result.push (key) } <span style="color:#0000ff;">return</span> result; }</pre> </div> <p> <strong>Object.getPrototypeOf () 函数</strong></p> <div> <pre><span style="color:#0000ff;">function</span> proto (object) { <span style="color:#0000ff;">return</span> !object? <span style="color:#0000ff;">null</span> : '__proto__' <span style="color:#0000ff;">in</span> object? object.__proto__ : <span style="color:#008000;">/*</span><span style="color:#008000;"> not exposed? </span><span style="color:#008000;">*/</span> object.constructor.prototype }</pre> </div> <p> <strong>bind 函数</strong></p> <div> <pre><span style="color:#0000ff;">var</span> slice = [].slice<span style="color:#0000ff;">function</span> bind (fn, bound_this) { <span style="color:#0000ff;">var</span> bound_args bound_args = slice.call (arguments, 2) <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">function</span>() { <span style="color:#0000ff;">var</span> args args = bound_args.concat (slice.call (arguments)) <span style="color:#0000ff;">return</span> fn.apply (bound_this, args) } }</pre> </div> <p> <strong>参考</strong></p> <ul> <li>W3CSchool</li> <li>MDN (Mozilla Developer Network)</li> <li>MSDN (Microsoft Software Development Network)</li> <li><a href="/misc/goto?guid=4959500523253139189" target="_blank">Understanding Javascript OOP</a>.</li> </ul> <div id="come_from"> 来自: <a id="link_source2" href="/misc/goto?guid=4959500523330971912" target="_blank">coolshell.cn</a> </div>