JavaScript面向對象深度剖析

jopen 11年前發布 | 20K 次閱讀 JavaScript開發 JavaScript

摘要: Javascript是一個類C的語言,他的面向對象的東西相對于C++/Java比較奇怪,但是其的確相當的強大,在 Todd 同學的對象的消息模型一文中我們已經可以看到一些端倪了。這兩天有個前同事總在問我Javascript面向...

    Javascript是一個類C的語言,他的面向對象的東西相對于C++/Java比較奇怪,但是其的確相當的強大,在 Todd 同學的“對象的消息模型”一文中我們已經可以看到一些端倪了。這兩天有個同學總在問我Javascript面向對象的東西,所以,索性寫篇文章讓他看去吧,這里這篇文章主要想從一個整體的角度來說明一下Javascript的面向對象的編程.

  初探

  我們知道Javascript中的變量定義基本如下:

  var name = 'Chen Hao';;

  var email = 'haoel(@)hotmail.com';

  var website = 'http://coolshell.cn';

  如果要用對象來寫的話,就是下面這個樣子:

  var chenhao = {

  name :'Chen Hao',

  email : 'haoel(@)hotmail.com',

  website : 'http://coolshell.cn'

  };

  于是,我就可以這樣訪問:

  //以成員的方式

  chenhao.name;

  chenhao.email;

  chenhao.website;

  //以hash map的方式

  chenhao["name"];

  chenhao["email"];

  chenhao["website"];

  關于函數,我們知道Javascript的函數是這樣的:

  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的動態語言。

  還有一種比較規范的寫法是:

  //我們可以看到, 其用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']

  上面的這些例子,我們可以看到這樣幾點:

  ◆ Javascript的數據和成員封裝很簡單。沒有類完全是對象操作。純動態!

  ◆ Javascript function中的this指針很關鍵,如果沒有的話,那就是局部變量或局部函數。

  ◆ Javascript對象成員函數可以在使用時臨時聲明,并把一個全局函數直接賦過去就好了。

  ◆ Javascript的成員函數可以在實例上進行修改,也就是說不同實例相同函數名的行為不一定一樣。

  屬性配置 – 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 }

  }

  );

  下面就說說這些屬性配置是什么意思。

  writable:這個屬性的值是否可以改。

  configurable:這個屬性的配置是否可以改。

  enumerable:這個屬性是否能在for…in循環中遍歷出來或在Object.keys中列舉出來。

  value:屬性值。

  get()/set(_value):get和set訪問器。

  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 = "
";

  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+ '
');

  }

  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);

  c.calculate('+');

  c.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) }

  }

原文地址:http://coolshell.cn/articles/6441.html

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!