gpt4 book ai didi

javascript - 使用可变数量的参数调用类对象

转载 作者:行者123 更新时间:2023-11-30 12:31:02 25 4
gpt4 key购买 nike

我正在为一项非常具体的任务制作我自己的类似 jQuery 的库。 (不想用jquery,更接近原生js)。

我需要一个解决方案来调用带有和不带有参数的类,在我的例子中是某些选择器。

我所提到的 - 类必须以两种方式工作:

myclass.function();

和:

myclass(selector).function();

类的初始化是这样的

(function(window){
var myclass = function( selector ){
return new myclass.model.build( selector );
};

myclass.model = myclass.prototype = {
constructor: myclass,
myfunction: function(){
alert("some function's alert");
}
};

myclass.model.build = function( selector ){
if( !selector )
return this;
/* Picking objects by selector */
};

window.myclass = myclass;
return myclass;
})(window);

最佳答案

jsFiddle Demo

有几种方法可以实现这一点。这是一种常见的方法,它是设置一个本地函数(“类”)的实例,该实例将其原型(prototype)配置为可扩展性对象,并将属性附加到它作为对象。

//use window and document shortcut
(function(win,doc){
//setup local function in order to extend
var jakeWeary = function(selector){
//force an instance to be returned when referenced
return new jakeWeary.fun.start(selector);
};
//allow prototype to be extended by referencing fun
jakeWeary.fun = jakeWeary.prototype = {
constructor : jakeWeary,
//use passed values to query
start : function(selector){
//query against present document
var nodes = doc.querySelectorAll(selector);
//mimic an array of matched elements
for(var i = 0; i < nodes.length;i++){
this[i] = nodes[i];
}
//return self for chaining
return this;
}
};
//extend function object in order to be used without calling instance
jakeWeary.div = function(content){
var div = document.createElement("div");
div.innerHTML = content;
return div;
};
//expose
win.jakeWeary = win.jk = jakeWeary;
})(window,document)

//call instance to match the selector `.d`
var $ = jakeWeary('.d');//lets use a fun variable like $ for this
//reference the third matched element, and then append a div created from a function on the
//jakeWeary function object
$[2].appendChild(jk.div("<p>Reinventing the wheel</p>"));
<div id="i">i</div>
<div class="d">d</div>
<div class="d">d</div>
<div class="d">d</div>

关于javascript - 使用可变数量的参数调用类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27697639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com