【发布时间】:2017-06-08 14:44:52
【问题描述】:
我正在尝试实现类似于 jQuery 的东西。
基本上,每当我对 DOM 元素做某事时,我都想使用包装对象的方法,而不是直接操作 DOM。
这是我目前所拥有的
HTML:
<a href='#!'></a>
JS:
var dd = function(selector)
{
return new dd.prototype.constructor(selector);
}
dd.prototype =
{
constructor: function(selector)
{
var nodes = document.querySelectorAll(selector);
for(var i = 0; i < nodes.length; i++)
this[i] = nodes[i];
this.length = nodes.length;
return Array.prototype.slice.call(this);
},
addClass: function(cl)
{
alert('a');
}
};
var a = dd('[href="#!"]');
a.addClass('asd');
问题:
- 我在浏览器控制台中收到错误消息,提示
a.addClass is not a function -
dd('a') instanceof dd === false而$('a') instanceof $ === true,所以我知道我的逻辑在这里有些错误。
很遗憾,我不太明白自己做错了什么。
【问题讨论】:
-
考虑使用 es6 类。它比使用
prototype简单得多。你的构造函数看起来很可疑,我很确定你不应该返回任何东西。a = dd()也应该是a = new dd()。 -
@Halcyon 我会使用 es6 类,但浏览器对它们的支持还不够好。构造函数应该返回一个数组,该数组包含数字索引上的 DOM 元素,并有一个 proto 包含我想使用的方法(基于 jQ 的做法)。目前我的数组看起来不错,但 proto 不包含 addClass。第一个函数定义返回一个新对象(或者至少应该返回),这样我就不必每次在对象中包装一个元素时都使用 new 。
-
如果你想创建类似的东西,看看 jQuery 的源代码 - 你可以在那里学到很多东西。
-
@wostex 干杯,我一直在这样做,但我想目前对我来说有点复杂。
标签: javascript jquery html