[英]Use functions and properties from one object in another object
創建了一個對象Blubb ,它必須要做一些事情。 這些對象有幾個。 現在有另一個對象BlubbWatcher ,當它不得不重置它時,必須從Blubb中重置一些內容。
我試圖創建prototype.functions
,然后考慮以后可以使用Object.create(Blubb)
來使用它們。 現在我可以使用函數,但是屬性為空/未定義,原因是我猜我在BlubbWatcher中沒有正確的Blubb實例
簡化示例來演示我的問題:
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>
如何在BlubbWatcher中使用Blubb的功能和屬性?
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
一起_.map
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.