2012-01-26 15 views
0

私はJavascriptを継承して練習してる、私の最初の試みは、次のコードされています。そのポイントにアクセス公共方法 - JavaScriptの継承

var base_class = function() 
{ 
    var _data = null; 

    function _get() { 
     return _data; 
    } 

    this.get = function() { 
     return _get(); 
    } 

    this.init = function(data) { 
    _data = data; 
    }  
} 

var new_class = function() { 

    base_class.call(this); 

    var _data = 'test'; 

    function _getData() { 
     return this.get(); 
    } 

    this.getDataOther = function() { 
     return _getData(); 
    } 

    this.getData = function() { 
     return this.get(); 
    } 

    this.init(_data); 
} 

new_class.prototype = base_class.prototype; 

var instance = new new_class(); 

alert(instance.getData()); 
alert(instance.getDataOther()); 

を私は私の解決策には本当に満足していますしかし、私は解決されていない1つの問題 があります。

"getDataOther"メソッドは、new_classの保護された "_getData"メソッドからパブリック "get"クラスにアクセスできないため、格納されたデータを基本クラス から返しません。

どうすれば実行できますか?

ありがとうございます。

Psの:あなたは(base_class_dataフィールドを上書き)this.init機能をコメントアウトし、new_classgetData機能だけで_dataを返すようならば、あなたは明確な得ることができる必要があり、私の下手な英語

答えて

1

を許しなさい変数。

var base_class = function() 
{ 
    var _data = null; 

    function _get() { 
     return _data; 
    } 

    this.get = function() { 
     return _get(); 
    } 

    this.init = function(data) { 
     _data = data; 
    }  
} 

var new_class = function() { 
    var self = this; //Some browsers require a separate this reference for 
         //internal functions. 
         //http://book.mixu.net/ch4.html 

    base_class.call(this); 

    var _data = 'test'; 

    function _getData() { 

     return self.get(); 
    } 

    this.getDataOther = function() { 
     return _getData(); 
    } 

    this.getData = function() { 
     return _data; //Changed this line to just return data 
         //Before, it did the same thing as _getData() 
    } 

    //this.init(_data); //Commented out this function (it was changing the base_class' data) 
} 

new_class.prototype = base_class.prototype; 

var instance = new new_class(); 

alert(instance.getData()); 
alert(instance.getDataOther()); 

あなたの英語力が道で結構です:)

+0

おかげで、これは=動作するようになりました)...しかし、なぜのgetData()は「ヌル」ではなく継承したクラスからの「テスト」とは? ?? – Moszeed

+0

'this.init(_data)'のコメントを外します。私はそれが私がそれが親の変数を見ていたことを確認できるようにコメントしました。 –

関連する問題