[英]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.