2017-07-19 52 views
0

在下面的代碼中面對繼承問題我是OOPS概念的新手,請幫助我。Javascript繼承不起作用

var testA = function() { 
    this._data = undefined 
}; 
testA.prototype.init = function(data) { 
    this._data = data; 
}; 
testA.prototype.get = function(data) { 
    if (this._data) { 
    return data 
    } 
}; 
var testB = function() {} 
testB.prototype = Object.create(testA); 
var instance = new testB(); 
testB.prototype.init = function(data) { 
    testA.prototype.init.call(this, data); 
}; 
testB.prototype.Somedata = function() { 
    testA.prototype.get(); 
} 
instance.init("testdata"); 
instance.Somedata() // here i am getting this._data is undefined 
  1. 當我打電話instance.init( 「TESTDATA」),現在它的設定值在父this._data。

  2. 當我打電話instance.Somedata()在這裏我得到未定義

可我知道可能是什麼原因?當我調用instance.Somedata()時,如何獲得this._data值。

+0

您剛更改了代碼?問題是'testA.init'不存在,現在你已經編輯了錯誤。 – adeneo

+0

是剛纔我編輯它 –

+0

我可以知道我怎麼能得到this._data值,當我打電話給instance.somedata() –

回答

0

起初:

testB.prototype = Object.create(testA); 

實例化一個功能,你可能想要麼實例化原型:

testB.prototype = Object.create(testA.prototype); 

或直接構造它:

testB.prototype =new testA; 

其次SomeData不返回任何東西,可能會這樣做,而且您還需要保持上下文:

testB.prototype.Somedata = function() { 
    return testA.prototype.get.call(this,"return"); 
} 

或者,即使我們做了上面的繼承權更容易:

testB.prototype.Somedata = function() { 
    return this.get("return"); 
} 
+0

感謝你的回覆讓我試試 –

+0

它的工作,但爲什麼我們需要使用call alwasy ?如果我們已經設置了數據? –

0

你使用的Object.create對構造函數,你應該使用它對抗的情況下,否則,你得到的回報功能而不是一個對象。

var TestA = function() { 
    this._data = undefined; 
}; 
TestA.prototype.init = function(data) { 
    this._data = data; 
}; 
TestA.prototype.get = function() { 
    return this._data; 
}; 

var instance = Object.create(new TestA()); 
instance.init('some'); 
instance.get(); 
+0

它仍然不工作我得到this._data是未定義的,當我打電話instance.get() –

+0

不知道,我剛剛複製這個代碼到控制檯,它工作正常。你能告訴我你的最新代碼嗎? – stevelacerda7