如果我想返回一个封装在原型(prototype)定义对象中的 HTML dom 元素,以便访问添加到原型(prototype)的方法,我将如何处理。 我想要实现的目标的更具体示例如下:
(function(window, document, undefined) {
var i;
var el;
var Dome = function(selector, getAllMatches) {
return Dome.core.init(selector, getAllMatches);
};
Dome.core = Dome.prototype = {
constructor: Dome,
el: "",
init: function(selector, getAllMatches) {
if (typeof arguments[0] !== "undefined") {
this.el = getElement(selector);
if (this.el instanceof Dome){
return this.el;
}
else{
return this.el;
}
}
}
.....
})(window, document);
我想要实现的是返回一个 Dome 实例而不是 this.el ,这样我就可以访问它的方法。我知道 jquery 做得很好,但我对 js 没有太多经验,对原型(prototype)的了解接近于 0。
最佳答案
听起来你想要一个 Factory ?
function Dome(element){
this.element = element;
this.getElement = function(){
return this.element;
}
}
Dome.factory = function(selector){
var el = getElement(selector);
return new Dome(el);
}
var d = Dome.factory('test');
alert(d.getElement());
+编辑+
既然你问了 jQuery 如何做到这一点,我只是快速浏览了一下......
所以主要的 jQuery 工厂($, jQuery)是;
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
}
然后,jQuery.fn.init 的原型(prototype)由 jQuery.fn 填充。
因此编辑我的原始答案以匹配此格式将是;
function Dome(element){
this.element = element;
}
Dome.core = {
getElement: function(){
return this.element;
}
};
Dome.prototype = Dome.core;
Dome.factory = function(selector){
var el = getElement(selector);
return new Dome(el);
}
var d = Dome.factory('test');
alert(d.getElement());
关于javascript - 返回封装在原型(prototype)类型对象 javascript 中的 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16567506/