[英]How can I assign initial data to some variables in literal object before use
我有一个做某事的文字对象,在使用任何方法之前,该对象必须将一些初始数据分配给变量。
var slideshow = {
slideshowBox: null,
slideImages: null,
slideImagesLen: 0,
init: function(){
this.slideshowBox = document.getElementById('slideshow');
this.slideImages = document.getElementById('images');
this.slideImagesLen = this.slideImages.children.length;
},
show: function(){
return this.slideImagesLen;
}
};
但是问题是,当使用其任何方法时,必须首先使用init
方法,然后再使用I可以使用任何其他方法,但是这种行为不是很好。
slideshow.init()
console.log(slideshow.show());
我也尝试使用以下方式:
(function(){
var slideshow = {
slideshowBox: null,
slideImages: null,
slideImagesLen: 0,
init: function(){
this.slideshowBox = document.getElementById('slideshow');
this.slideImages = document.getElementById('images');
this.slideImagesLen = this.slideImages.children.length;
},
show: function(){
return this.slideImagesLen;
}
};
slideshow.init();
})();
但是,有一些这样的错误this.slideImages is null
, slideshow.show is not a function
我希望有任何一种方法可以在使用任何方法之前自动调用init
方法,而无需手动调用它。
您应该在此处尝试将原型继承与构造函数一起使用。
(function(){
var Slideshow = function () {
this.slideshowBox = document.getElementById('slideshow');
this.slideImages = document.getElementById('images');
this.slideImagesLen = this.slideImages.children.length;
};
Slideshow.prototype.show = function () {
return this.slideImagesLen;
};
var slideShowInstance = new Slideshow();
slideShowInstance.show();
})();
我实际上会更进一步以使其更可扩展
var Slideshow = function (slideShowId, images) {
this.slideshowBox = slideShowId;
this.slideImages = images;
this.slideImagesLen = this.slideImages.children.length;
};
var slideShowId = document.getElementById('slideshow'),
images = document.getElementById('images');
var slideShowInstance = new Slideshow(slideShowId, images);
在函数slides
调用_slideshow.init
后,尝试返回Object
_slideshow
var slides = function(options) { return (function(opts) { var _slideshow = opts || { slideshowBox: null, slideImages: null, slideImagesLen: 0, init: function() { this.slideshowBox = document.getElementById('slideshow'); this.slideImages = document.getElementById('images'); this.slideImagesLen = this.slideImages.children.length; }, show: function() { return this.slideImagesLen; } }; _slideshow.init(); return Object.create(_slideshow) }(options)) }; var slideshow = slides(); console.log("slideImagesLen:", slideshow.show(), "slideshow:", slideshow);
<div id="slideshow"> <div id="images"> <img src="http://lorempixel.com/50/50/nature" /> </div> </div>
有两种方法。 例如:
var slideshow = {
...
init: function () {
...
return this;
}
...
}.init();
或者,如果仍然过于手动,则可以在对象文字中简单地使用IIFE:
var slideshow = {
...
init: (function init () {
...
return init;
}())
...
}
在这两种情况下,创建对象之前,引用的HTML元素都必须存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.