2010-04-29 56 views
4

我需要從另一個固有的類。javascript inherance?與私人變數和方法

父具有私有變量「_data」和私有方法「_test」和公共方法「添加」 現在孩子有一個公共方法「添加」,它使用私人方法從父母「_test」和私人變種「_數據」。

我該怎麼做?

var Parent = function(){ 
    var _data = {}; 
    var _test = function(){alert('test')}; 
    this.add = function(){alert('add from parent')} 
} 

var Child = function(){ 
    this.add = function(){// here uses the _data and _test from the Parent class 
     alert('add from child') 
    } 
} 

// something to inherent Child from Parent 
// instance Child and use the add method 

而且我想我錯過了原型概念(Javascript inheritance

回答

0

一個簡單的繼承:

function createChild(){ 
    Child.prototype=new Parent() 
    return new Child() 
} 

這樣你會得到家長的新鮮初始化爲每一個孩子。

0

有一些圖書館與OOP般的功能擴展的JavaScript。也許你在JS繼承中發現了John Resigs Blog Entry(通過base2和Prototype)。

+0

我只能像我使用的框架一樣使用jquery。我寧願只堅持1 ... – 2010-04-29 23:29:39

1

通常,您在JavaScript中進行繼承的方式是將Child類的prototype屬性分配給Parent對象的實例。所以,你會定義構造函數的Child

function Child() { /* initialization yadda yadda */ }

,然後做到這一點:

Child.prototype = new Parent();

這是或多或少相當於Class Child extends Parent其他語言 - 兒童則有方法,成員和通過閉包,一個父對象的私有成員。

這裏有一些棘手的問題。其中之一是在構造函數中完成初始化。顯式調用Child構造函數中的父構造函數(function Child() { Parent(); })似乎是最明顯的方法,但由於this被處理並從初始化返回(函數Parent什麼是?),所以會出現問題。您可以解決此通過使用Functionapply方法(每個函數可以訪問):

function Child() { Parent.apply(this,arguments); //initialization unique to Child goes here }

(見http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/apply更多關於適用)

但我通常做的事情是這樣的將類的所有初始化分解成一個獨立的「init」函數,該函數將排序替換構造函數。

function Parent() { this.init(); }

Parent.prototype.init = function() { /* initialization yadda yadda */ }

這樣一來,這簡直與其他內容一起繼承了......或者我可以寫一個新的調用,如果我喜歡舊的:

Child.prototype.init = function() { Parent.prototype.init.apply(this,arguments); /* insert stuff unique to child constructor here */ }

其他棘手的一點是訪問Parent的私人會員。除了Parent的方法外,你真的不能這樣做。它們是真正的私有的,不是「受保護的」,「子類」除了通過它們繼承的方法之外不能看到它們。有一些寫作方式,但這可能是另一個Q/A,最簡單的方法就是確保你設計好你的Parent