从扩展类中的受保护方法访问扩展类中的公共方法-javascript继承
我正在练习Javascript继承,我的第一次尝试是以下代码:从扩展类中的受保护方法访问扩展类中的公共方法-javascript继承,javascript,inheritance,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 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”方法不会从基类返回存储的数据,
因为我无法从新\u类中受保护的“\u getData”方法访问公共“get”类
我怎样才能让它跑起来
提前谢谢
注:如果您注释掉
this.init
函数(覆盖基本类
数据
字段)并使新类
的获取数据
函数只返回\u数据
,请原谅我的英语不好
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());
顺便说一句,你的英语很好:)谢谢,现在可以用了=)。。。但是为什么getData()现在是“null”而不是扩展类中的“test”。我对它进行了注释,以便确保它看到了父变量。