Javascript继承:推送未定义的
在上面的javascript代码片段中,我遇到了“无法读取未定义”错误的属性“push”Javascript继承:推送未定义的,javascript,oop,inheritance,Javascript,Oop,Inheritance,在上面的javascript代码片段中,我遇到了“无法读取未定义”错误的属性“push” 是我的继承观念错了吗?任何人都可以帮助解决此继承问题吗您的代码中有几个错误/不准确之处: 这样写来保存原型继承更干净 testA = function(){ this._data = []; } testA.prototype.add = function(data){ this._data.push(data) // Here i am facing this._data is undefined }
是我的继承观念错了吗?任何人都可以帮助解决此继承问题吗您的代码中有几个错误/不准确之处:
testA = function(){
this._data = [];
}
testA.prototype.add = function(data){
this._data.push(data) // Here i am facing this._data is undefined
}
testB = function(){}
testB.prototype = Object.create(testA);
var instance = new testB;
testB.prototype.pushData = function(data){
instance.prototype.add(data);
}
function (data){
instance.prototype.add(data);
}
instance.pushData("someData")
实例
对象具有\u数据
属性,必须调用
首先是testB
中的testA
(父项)
testB.prototype = Object.create(testA.prototype);
testB = function() { testA.call(this); }
testB
内部,您可以使用this
引用父级(testA
)属性,以便调用add()
函数:this.add(数据)
首先在testB
的属性中搜索此函数,然后在testA
原型对象中通过testB
的\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>引用(参见上文第1点)
testA=function(){
这是._data=[];
}
testA.prototype.add=函数(数据){
此._data.push(数据);
//console.log(此._数据);
}
testB=函数(){
测试调用(这个);
}
testB.prototype=Object.create(testA.prototype);
testB.prototype.pushData=函数(数据){
添加(数据);
}
var instance=newtestb();
pushData(“someData”);
console.log(实例数据)代码>谢谢您的回复欢迎您!自由投票或标记为有用的答案:)Hi curveball one澄清假设testB是否也有相同的方法,如add
,现在我想从父级和子级执行相同的方法,所以在这种情况下我需要做什么?在本例中,我需要从testA和testB调用add方法testA=function(){this._data=[];}testA.prototype.add=function(data){console.info(“testA方法”)this._data.push(data);//console.log(this._data);}testB=function(){testA.call(this);}testB.prototype=Object.create(testA.prototype);testB.prototype.pushData=function(data){this.add(data);}testB.prototype.add=function(){console.info(“testB方法”)}var实例=newtestb();pushData(“someData”);console.log(实例数据)代码>通常,在这种情况下,您需要调用child的add(),在child的add()中,您必须调用父级的add(),就像我对构造函数所做的那样。检查更新的答案。另外,如果您希望这两个方法完全独立并从不同的上下文中调用,只需从各自的对象中调用它们:如果您需要testA中的add(),请创建一个NewTesta对象并调用其add()。testB也是如此。
function (data){ instance.prototype.add(data); }