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