[英]access public method in extended class from protected method in extending class - javascript inheritance
我正在用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());
到那時我真的很滿意我的解決方案,但是有一個我沒有解決的問題。
“ getDataOther”方法不會從基類返回存儲的數據,因為我無法從new_class中受保護的“ _getData”方法訪問公共的“ get”類。
我該如何運行?
提前致謝。
詩:請原諒我的英語不好
如果您注釋掉this.init
函數(覆蓋base_class
_data
場),使new_class
的getData
函數只是返回_data
,你應該能夠得到不同的變量。
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());
順便說一下,你的英語很好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.