2017-09-20 20 views
0

創建對象Blubb必須做一些事情。有幾個這樣的對象。現在有另一個對象BlubbWatcher當它必須重置一些東西從Blubb使用另一個對象中一個對象的功能和屬性

我試圖創建prototype.functions,並認爲我可以稍後使用它們,使用Object.create(Blubb)。現在我可以使用的功能,但屬性爲空/未定義的原因,我想我沒有的Blubb正確的實例中BlubbWatcher

簡單的例子來證明我的問題:

var Blubb = function(element) { 
 
    this.element = element; 
 
    this.header = 'hello world'; 
 
    this.init(); 
 
}; 
 

 
Blubb.prototype.init = function() { 
 
    console.log(this.header); 
 
}; 
 

 
//////////////// 
 
var BlubbWatcher = function(sections){ 
 
    this.sections = sections; 
 
    this.Blubb = Object.create(Blubb); 
 
    Array.prototype.forEach.call(
 
     this.sections, 
 
     (function (element) { 
 
      // call Blubb.init from here makes header undefined 
 
      console.log(' - next log is undefined - ') 
 
      this.Blubb.prototype.init(element); 
 
     }).bind(this) 
 
    ); 
 
}; 
 

 
////////////////// 
 
var sections = document.querySelectorAll('section'); 
 
Array.prototype.forEach.call(
 
    sections, 
 
    function (element, index) { 
 
     new Blubb(element); 
 
    } 
 
); 
 

 
new BlubbWatcher(sections);
<section>section</section>

我怎樣才能在使用的功能和屬性從Blubb BlubbWatcher

+0

你只想讓'BlubbWatcher'包含一個或多個'Blubb'對象嗎?或者你想要某種類似繼承的關係? –

+0

@FrankModica我想擁有類似繼承的關係 – caramba

+0

除非您通過第二個參數明確指定/傳遞它們,否則Object.create'不會創建屬性(請參閱[文檔](https://developer.mozilla.org)/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create)。但是,如果你已經有了一個構造函數(基類),你可以在子類的構造函數中調用它。然後,您將擁有從基類自動複製/從基類繼承的屬性。或者,您可以使用'new'運算符*將基類實例化爲子類的成員:'this.Blubb = new Blubb();' – hindmost

回答

1
var Blubb = function(element, header) { 
    this.element = element; 
    this.header = header; 
    this.init(); 
}; 

Blubb.prototype.init = function() { 
    console.log(this.header, 'header'); 
}; 

//////////////// 
var BlubbWatcher = function(blubbs){ 
    this.blubbs = blubbs; 
    Array.prototype.forEach.call(
     this.blubbs, 
     function (element) { 
      console.log(' - next log is NOT undefined :) - ') 
      element.init(); 
     } 
    ); 
}; 

////////////////// 
var sections = document.querySelectorAll('section'); 
var blubbs = Array.prototype.map.call(
    sections, 
    function (element) { 
     return new Blubb(
      element, 
      document.querySelector('header') 
     ); 
    } 
); 

new BlubbWatcher(blubbs); 

我已重寫您的代碼。發生的事情是,您實際上在BlubbWatcher中創建了Blubb的新實例,而不是使用以前創建的實例。

爲了使它工作,我已經在章節中使用了.map並獲得了一個包含Blubb實例的數組,然後我將這些實例添加到了BlubbWatcher中。

如果您在瀏覽器中並且必須支持舊瀏覽器,請考慮使用lodash庫和_.map

+0

我嘗試了您的代碼https://jsfiddle.net/j7cpokar/,但瀏覽器控制檯顯示:「Uncaught TypeError:sections.map不是函數」 – caramba

+1

我已更新我的代碼和jsfiddle https:// jsfiddle .net/j7cpokar/2 /,它爲我工作:) –

相關問題