自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

JavaScript面向對象編程

開發(fā) 開發(fā)工具
在這篇教程中,你將學習基于JavaScript的面向對象編程。其中的代碼示例是基于EcmaScript 5(JavaScript的標準定義)來實現(xiàn)。

隨著HTML5標準的成熟和在移動開發(fā)領域的大規(guī)模使用,JavaScript正成為Web開發(fā)領域最熱門的開發(fā)語言,而且隨著NodeJS等技術的發(fā)展,JavaScript的應用也從傳統(tǒng)前端開發(fā)領域延伸到了服務器端開發(fā)。但同時需要注意的是,我們項目中的JavaScript代碼規(guī)模也變得越來越大和更加復雜。這就要求開發(fā)人員能夠編寫高效且可維護的JavaScript代碼,雖然JavaScript不像Java那樣對面向對象設計有那么好的支持,但我們可以通過在JavaScript中應用這些面向對象的設計模式,來使我們寫出更優(yōu)秀的JavaScript代碼。

在這篇教程中,你將學習基于JavaScript的面向對象編程。其中的代碼示例是基于EcmaScript 5(JavaScript的標準定義)來實現(xiàn)。

Java與JavaScript的比對

對象類型定義- Object Type

  1. function MyType(){    if (!(this instanceof MyType))        throw new Error("Constructor can’t be called as a function"); 
  2. }var myInstance = new MyType(); 
  3. MyType(); // Error: Constructor can’t be called as a function 

在Eclipse的JavaScript視圖中,構造器,實例成員,靜態(tài)成員和內部函數(shù)都能被識別,并在Outline視圖中顯示出來。

實例成員 - Instance Members

通過"new"關鍵字可以創(chuàng)建一個實例對象,而實例成員(變量或方法)能夠通過這個實例對象來訪問。實例成員可以通過"this"關鍵字,原型(prototype),構造器或Object.defineProperty來定義。

  1. function Cat(name){    var voice = "Meow";    this.name = name;    this.say = function(){      return voice; 
  2.     } 
  3. Cat.prototype.eat = function(){    return "Eating"
  4. }var cat = new Cat("Fluffy");Object.defineProperty(cat, "numLegs",{value: 4,writable:true,enumerable:true,configurable:tr 
  5. ue});console.log(cat.name); // Fluffyconsole.log(cat.numLegs); // 4console.log(cat.say()); // Meowconsole.log(cat.eat()); // Eating 

靜態(tài)成員 - Static Members

JavaScript中并不直接支持靜態(tài)成員。你可以通過構造器來創(chuàng)建靜態(tài)成員。靜態(tài)成員不允許通過"this"關鍵字直接訪問。

公共靜態(tài)成員

  1. function Factory(){ 
  2. }// public static methodFactory.getType = function (){    return "Object Factory"
  3. };// public static fieldFactory.versionId = "F2.0"
  4. Factory.prototype.test = function(){    console.log(this.versionId); // undefined 
  5.     console.log(Factory.versionId); // F2.0 
  6.     console.log(Factory.getType()); // Object Factory}var factory = new Factory(); 
  7. factory.test(); 

私有靜態(tài)成員

  1. var Book = (function () {    // private static field 
  2.     var numOfBooks = 0;    // private static method 
  3.     function checkIsbn(isbn) {        if (isbn.length != 10 && isbn.length != 13)            throw new Error("isbn is not valid!"); 
  4.     }    function Book(isbn, title) { 
  5.         checkIsbn(isbn);        this.isbn = isbn;        this.title = title; 
  6.         numOfBooks++;        this.getNumOfBooks = function () {            return numOfBooks; 
  7.         } 
  8.     }    return Book; 
  9. })();var firstBook = new Book("0-943396-04-2""First Title");console.log(firstBook.title); // First Titleconsole.log(firstBook.getNumOfBooks()); // 1var secondBook = new Book("0-85131-041-9""Second Title");console.log(firstBook.title); // First Titleconsole.log(secondBook.title); // Second Titleconsole.log(firstBook.getNumOfBooks()); // 2console.log(secondBook.getNumOfBooks()); // 2 

抽象類型 - Abstract Types

JavaScript是一個弱類型語言,所以當你聲明一個變量時,不需要指定它的類型。這就減弱了對于像接口這樣的抽象類型的依賴。但有時候,你仍然希望使用抽象類型來將一些共有的功能放在一起,并采用繼承的機制,讓其他類型也具有相同的功能,你可以參考下面的示例:

  1. (function(){    var abstractCreateLock = false;    // abstract type 
  2.     function BaseForm(){        if(abstractCreateLock)            throw new Error("Can’t instantiate BaseForm!"); 
  3.     } 
  4.  
  5.     BaseForm.prototype = {}; 
  6.     BaseForm.prototype.post = function(){        throw new Error("Not implemented!"); 
  7.     }    function GridForm(){ 
  8.     } 
  9.  
  10.     GridForm.prototype = new BaseForm(); 
  11.     abstractCreateLock = true
  12.     GridForm.prototype.post = function(){        // ... 
  13.         return "Grid is posted."
  14.     }    window.BaseForm = BaseForm;    window.GridForm = GridForm; 
  15. })();var myGrid = new GridForm();console.log(myGrid.post()); // Grid is posted.var myForm = new BaseForm(); // Error: Can’t instantiate BaseForm! 

接口 - Interfaces

JavaScript同樣沒有對接口的直接支持。你可以通過下面代碼中實現(xiàn)的機制來定義接口。

  1. var Interface = function (name, methods) {    this.name = name;    // copies array 
  2.     this.methods = methods.slice(0); 
  3. }; 
  4.  
  5. Interface.checkImplements = function (obj, interfaceObj) {    for (var i = 0; i < interfaceObj.methods.length; i++) {        var method = interfaceObj.methods[i];        if (!obj[method] || typeof obj[method] !=="function"
  6.             thrownewError("Interfacenotimplemented! Interface: " + interfaceObj.name + " Method: " + method); 
  7.     } 
  8. };var iMaterial = new Interface("IMaterial", ["getName""getPrice"]);function Product(name,price,type){ 
  9.     Interface.checkImplements(this, iMaterial);    this.name = name;    this.price = price;    this.type = type; 
  10.  
  11. Product.prototype.getName = function(){    return this.name
  12. }; 
  13. Product.prototype.getPrice = function(){    return this.price; 
  14. };var firstCar = new Product("Super Car X11",20000,"Car");console.log(firstCar.getName()); // Super Car X11delete Product.prototype.getPrice;var secondCar = new Product("Super Car X12",30000,"Car"); // Error: Interface not implemented! 

單例對象 - Singleton Object

如果你希望在全局范圍內只創(chuàng)建一個某一類型的示例,那么你可以有下面兩種方式來實現(xiàn)一個單例。

  1. var Logger = { 
  2.     enabled:true
  3.     log: function(logText){      if(!this.enabled)        return;      if(console && console.log)        console.log(logText);      else 
  4.         alert(logText); 
  5.     } 
  6. 或者 
  7. function Logger(){ 
  8. Logger.enabled = true
  9. Logger.log = function(logText){    if(!Logger.enabled)        return;    if(console && console.log)        console.log(logText);    else 
  10.         alert(logText); 
  11. }; 
  12. Logger.log("test"); // testLogger.enabled = false
  13. Logger.log("test"); // 

創(chuàng)建對象 - Object Creation

通過new關鍵字創(chuàng)建

可以使用"new"關鍵字來創(chuàng)建內置類型或用戶自定義類型的實例對象,它會先創(chuàng)建一個空的實例對象,然后再調用構造函數(shù)來給這個對象的成員變量賦值,從而實現(xiàn)對象的初始化。

  1. //or var dog = {};//or var dog = new MyDogType();var dog = new Object(); 
  2. dog.name = "Scooby"
  3. dog.owner = {}; 
  4. dog.owner.name = "Mike"
  5. dog.bark = function(){   return "Woof"
  6. };console.log(dog.name); // Scoobyconsole.log(dog.owner.name); // Mikeconsole.log(dog.bark()); // Woof 

通過字面量直接創(chuàng)建

通過字面量創(chuàng)建對象非常簡單和直接,同時你還可以創(chuàng)建嵌套對象。

  1. var dog = { 
  2.   name:"Scoobyî"
  3.   owner:{ 
  4.     name:"Mike" 
  5.   }, 
  6.   bark:function(){    return "Woof"
  7.   } 
  8. };console.log(dog.name); // Scoobyconsole.log(dog.owner.name); // Mikeconsole.log(dog.bark()); // Woof 

成員作用域 - Scoping

私有字段 - Private Fields

在JavaScript中沒有對私有字段的直接支持,但你可以通過構造器來實現(xiàn)它。首先將變量在構造函數(shù)中定義為私有的,任何需要使用到這個私有字段的方法都需要定義在構造函數(shù)中,這樣你就可以通過這些共有方法來訪問這個私有變量了。

  1. function Customer(){  // private field 
  2.   var risk = 0;  this.getRisk = function(){    return risk; 
  3.   };  this.setRisk = function(newRisk){ 
  4.     risk = newRisk; 
  5.   };  this.checkRisk = function(){    if(risk > 1000)      return "Risk Warning";    return "No Risk"
  6.   }; 
  7.  
  8. Customer.prototype.addOrder = function(orderAmount){  this.setRisk(orderAmount + this.getRisk());  return this.getRisk(); 
  9. };var customer = new Customer();console.log(customer.getRisk()); // 0console.log(customer.addOrder(2000)); // 2000console.log(customer.checkRisk()); // Risk Warning 

私有方法 - Private Methods

私有方法也被稱作內部函數(shù),往往被定義在構造體中,從外部無法直接訪問它們。

  1. function Customer(name){  var that = this;  var risk = 0;  this.name = name;  this.type = findType();  // private method 
  2.   function findType() {     console.log(that.name);     console.log(risk);     return "GOLD"
  3.    } 

或者

  1. function Customer(name){  var that = this;  var risk = 0;  this.name = name;  // private method 
  2.   var findType = function() {     console.log(that.name);     console.log(risk);     return "GOLD"
  3.   };  this.type = findType(); 
  4. }var customer = new Customer("ABC Customer"); // ABC Customer 
  5.  // 0console.log(customer.type); // GOLDconsole.log(customer.risk); // undefined 

如果私有內部函數(shù)被實例化并被構造函數(shù)返回,那么它將可以從外部被調用。

  1. function Outer(){  return new Inner();  //private inner 
  2.   function Inner(){     this.sayHello = function(){        console.log("Hello"); 
  3.      } 
  4.    } 
  5. (new Outer()).sayHello(); // Hello 

特權方法 - Privileged Methods

原型方法中的一切都必須是公共的,因此它無法調用類型定義中的私有變量。通過在構造函數(shù)中使用"this."聲明的函數(shù)稱為特權方法,它們能夠訪問私有字段,并且可以從外部調用。

  1. function Customer(orderAmount){  // private field 
  2.   var cost = orderAmount / 2;  this.orderAmount = orderAmount;  var that = this;  // privileged method 
  3.   this.calculateProfit = function(){    return that.orderAmount - cost; 
  4.   }; 
  5.  
  6. Customer.prototype.report = function(){  console.log(this.calculateProfit()); 
  7. };var customer = new Customer(3000); 
  8. customer.report(); // 1500 

公共字段 - Public Fields

公共字段能夠被原型或實例對象訪問。原型字段和方法被所有實例對象共享(原型對象本身也是被共享的)。當實例對象改變它的某一個字段的值時,并不會改變其他對象中該字段的值,只有直接使用原型對象修改字段,才會影響到所有實例對象中該字段的值。

  1. function Customer(name,orderAmount){  // public fields 
  2.   this.name = name;  this.orderAmount = orderAmount; 
  3.  
  4. Customer.prototype.type = "NORMAL"
  5. Customer.prototype.report = function(){  console.log(this.name);  console.log(this.orderAmount);  console.log(this.type);  console.log(this.country); 
  6. }; 
  7.  
  8. Customer.prototype.promoteType = function(){  this.type = "SILVER"
  9. };var customer1 = new Customer("Customer 1",10);// public fieldcustomer1.country = "A Country"
  10. customer1.report(); // Customer 1 
  11.                      // 10 
  12.                      // NORMAL 
  13.                      // A Countryvar customer2 = new Customer("Customer 2",20); 
  14. customer2.promoteType();console.log(customer2.type); // SILVERconsole.log(customer1.type); // NORMAL 

公共方法 - Public Methods

原型方法是公共的,所有與之關聯(lián)的對象或方法也都是公共的。

  1. function Customer(){  // public method 
  2.   this.shipOrder = function(shipAmount){     return shipAmount; 
  3.   }; 
  4. }// public methodCustomer.prototype.addOrder = function (orderAmount) {    var totalOrder = 0;    for(var i = 0; i < arguments.length; i++) { 
  5.       totalOrder += arguments[i]; 
  6.     }    return totalOrder; 
  7.   };var customer = new Customer();// public methodcustomer.findType = function(){   return "NORMAL"
  8. };console.log(customer.addOrder(25,75)); // 100console.log(customer.shipOrder(50)); // 50console.log(customer.findType()); // NORMAL 

繼承 - Inheritance

有幾種方法可以在JavaScript中實現(xiàn)繼承。其中"原型繼承"——使用原型機制實現(xiàn)繼承的方法,是最常用的。如下面示例:

  1. function Parent(){  var parentPrivate = "parent private data";  var that = this;  this.parentMethodForPrivate = function(){     return parentPrivate; 
  2.   };  console.log("parent"); 
  3.  
  4. Parent.prototype = { 
  5.   parentData: "parent data"
  6.   parentMethod: function(arg){    return "parent method"
  7.   }, 
  8.   overrideMethod: function(arg){    return arg + " overriden parent method"
  9.   } 
  10. }function Child(){  // super constructor is not called, we have to invoke it 
  11.   Parent.call(this);  console.log(this.parentData);  var that = this;  this.parentPrivate = function(){     return that.parentMethodForPrivate(); 
  12.   };  console.log("child"); 
  13. }//inheritanceChild.prototype = new Parent();// parentChild.prototype.constructor = Child;//lets add extented functionsChild.prototype.extensionMethod = function(){  return "child’s " + this.parentData; 
  14. };//override inherited functionsChild.prototype.overrideMethod = function(){  //parent’s method is called 
  15.   return "Invoking from child" + Parent.prototype. 
  16.   overrideMethod.call(this, " test"); 
  17. };var child = new Child();// parent// parent data 
  18.  // childconsole.log(child.extensionMethod()); //child’s parent dataconsole.log(child.parentData); //parent dataconsole.log(child.parentMethod()); //parent methodconsole.log(child.overrideMethod()); //Invoking from child testoverriden parent methodconsole.log(child.parentPrivate()); // parent private dataconsole.log(child instanceof Parent); //trueconsole.log(child instanceof Child); //true 

當一個成員字段或函數(shù)被訪問時,會首先搜索這個對象自身的成員。如果沒有找到,那么會搜索這個對象對應的原型對象。如果在原型對象中仍然沒有找到,那么會在它的父對象中查找成員和原型。這個繼承關系也被成為 "原型鏈"。下面這張圖就反映了原型鏈的繼承關系。

模塊化 - Modularization

當我們的項目中,自定義的對象類型越來越多時,我們需要更有效地組織和管理這些類定義,并控制他們的可見性,相互依賴關系以及加載順序。"命名空間"和"模塊"能夠幫助我們很好地解決這個問題。(EcmaScript 6已經(jīng)實現(xiàn)了模塊系統(tǒng),但因它還沒有被所有瀏覽器實現(xiàn),此處我們仍以ES5為例來進行說明)

命名空間 - Namespaces

JavaScript中并沒有命名空間的概念。我們需要通過對象來創(chuàng)建命名空間,并將我們定義的對象類型放入其中。

  1. //create namespacevar myLib = {}; 
  2. myLib.myPackage = {};//Register types to namespacemyLib.myPackage.MyType1 = MyType1; 
  3. myLib.myPackage.MyType2 = MyType2; 

模塊 - Modules

模塊被用來將我們的JavaScript代碼分解到包中。模塊可以引用其他模塊或將自己定義的對象類型對外暴露,以供其他模塊使用。同時它能夠用來管理模塊間的依賴關系,并按照我們指定的順序進行加載。目前有一些第三方庫可以用來實現(xiàn)模塊的管理。

下面的例子中,我們在模塊里定義新的類型,并且引用其他模塊并將自身的公共類型對外暴露。

  1. Module.define("module1.js"
  2.                ["dependent_module1.js","dependent_module2.js",...],               function(dependentMod1, dependentMod2) {//IMPORTS 
  3.  
  4.   //TYPE DEFINITIONS 
  5.   function ExportedType1(){    // use of dependent module’s types 
  6.     var dependentType = new dependentMod1.DependentType1(); 
  7.     ... 
  8.   }  function ExportedType2(){ 
  9.   } 
  10.  
  11.   ...  // EXPORTS 
  12.   return { ExportedType1: ExportedType1, ExportedType2:ExportedType2,...}; 
  13. });//To use a module (can work asynchronously or synchronously):Module.use(["module1.js"], function(aModule){ 
  14.   console.log("Loaded aModule!");  var AType = aModule.AnExportedType;  var atype1Instance = new AType(); 
  15. }); 

自定義異常 - Custom Exceptions

JavaScript中有一些內部定義的異常,如Error、TypeError和SyntaxError。它們會在運行時被創(chuàng)建和拋出。所有的異常都是"unchecked"。一個普通的對象也可以被用作一個異常,并在throw語句中拋出。因此,我們可以創(chuàng)建自己定義的異常對象,并且在程序中捕獲它們進行處理。一個異常處理的***實踐是,擴展JavaScript中標準的Error對象。

  1. function BaseException() {} 
  2. BaseException.prototype = new Error(); 
  3. BaseException.prototype.constructor = BaseException; 
  4. BaseException.prototype.toString = function() {  // note that name and message are properties of Error 
  5.   return this.name + ":"+this.message; 
  6. };function NegativeNumberException(value) {  this.name = "NegativeNumberException";  this.message = "Negative number!Value: "+value; 
  7. NegativeNumberException.prototype = new BaseException(); 
  8. NegativeNumberException.prototype.constructor = NegativeNumberException;function EmptyInputException() {  this.name = "EmptyInputException";  this.message = "Empty input!"
  9. EmptyInputException.prototype = new BaseException(); 
  10. EmptyInputException.prototype.constructor = EmptyInputException;var InputValidator = (function() {  var InputValidator = {}; 
  11.   InputValidator.validate = function(data) {    var validations = [validateNotNegative, validateNotEmpty];    for (var i = 0; i < validations.length; i++) {      try { 
  12.         validations[i](data); 
  13.       } catch (e) {        if (e instanceof NegativeNumberException) {          //re-throw 
  14.           throw e; 
  15.         } else if (e instanceof EmptyInputException) {          // tolerate it 
  16.           data = "0"
  17.         } 
  18.       } 
  19.     } 
  20.   };  return InputValidator;  function validateNotNegative(data) {    if (data < 0)      throw new NegativeNumberException(data) 
  21.   }  function validateNotEmpty(data) {    if (data == "" || data.trim() == "")      throw new EmptyInputException(); 
  22.   } 
  23. })();try { 
  24.   InputValidator.validate("-1"); 
  25. } catch (e) {  console.log(e.toString()); // NegativeNumberException:Negative number!Value: -1 
  26.   console.log("Validation is done."); // Validation is done.} 

自定義事件 - Custom Events

自定義事件能夠幫助我們減小代碼的復雜度,并且有效地進行對象之間的解耦。下面是一個典型的自定義事件應用模式:

  1. function EventManager() {}var listeners = {}; 
  2.  
  3. EventManager.fireEvent = function(eventName, eventProperties) {  if (!listeners[eventName])    return;  for (var i = 0; i < listeners[eventName].length; i++) { 
  4.     listeners[eventName][i](eventProperties); 
  5.   } 
  6. }; 
  7.  
  8. EventManager.addListener = function(eventName, callback) {  if (!listeners[eventName]) 
  9.     listeners[eventName] = []; 
  10.   listeners[eventName].push(callback); 
  11. }; 
  12.  
  13. EventManager.removeListener = function(eventName, callback) {  if (!listeners[eventName])    return;  for (var i = 0; i < listeners[eventName].length; i++) {    if (listeners[eventName][i] == callback) {      delete listeners[eventName][i];      return
  14.     } 
  15.   } 
  16. }; 
  17.  
  18. EventManager.addListener("popupSelected"function(props) {  console.log("Invoked popupSelected event: "+props.itemID); 
  19. }); 
  20. EventManager.fireEvent("popupSelected", { 
  21.   itemID: "100"}); //Invoked popupSelected event: 100 

 【本文是51CTO專欄作者“陳逸鶴”的原創(chuàng)文章,如需轉載請聯(lián)系作者本人(微信公眾號:techmask)】

戳這里,看該作者更多好文

責任編輯:武曉燕 來源: 51CTO專欄
相關推薦

2012-01-17 09:34:52

JavaScript

2012-02-27 09:30:22

JavaScript

2011-05-25 10:21:44

Javascript

2011-05-25 10:59:26

Javascript繼承

2010-10-08 09:13:15

oop模式JavaScript

2011-06-28 14:11:33

JavaScript

2011-05-25 11:15:02

Javascript繼承

2010-11-17 11:31:22

Scala基礎面向對象Scala

2023-02-22 18:06:35

函數(shù)javascript面向對象編程

2019-11-18 17:05:02

JavaScript面向對象程序編程Java

2022-07-30 23:41:53

面向過程面向對象面向協(xié)議編程

2021-10-21 18:47:37

JavaScript面向對象

2012-12-13 11:01:42

IBMdW

2011-05-13 11:05:52

javascript

2011-05-13 12:38:58

javascript

2011-05-13 09:58:46

javascript

2011-05-13 10:51:25

javascript

2011-05-13 11:17:18

javascript

2011-05-13 11:27:59

javascript

2012-12-18 09:24:47

點贊
收藏

51CTO技術棧公眾號