我不知道从哪里开始,但我想要或需要的是 HTMLElement 的包装函数,所以我不扩展 HTMLElement 类,而是扩展我自己的对象,然后检查 has class 以查看元素是否有类等等等,但我的代码根本不起作用它说 $(...).hasClass 不是函数
$ = function(a, b) {
this.$el = document.querySelector(a);
return this;
}
Object.assign($.prototype, {
hasClass: function(selector) {
return this.$el.classList.contains(selector);
}
})
console.log($('#list').hasClass('list'));
最佳答案
你快到了 - 问题是独立表达式
$('#list')
将具有 window
的默认调用上下文($
函数中的 this
值)。如果您想创建一个可以使用原型(prototype)方法的实例,请在调用 $
之前放置 new
:
const $ = function(a, b) {
this.$el = document.querySelector(a);
}
Object.assign($.prototype, {
hasClass: function(selector) {
return this.$el.classList.contains(selector);
}
})
console.log(new $('#list').hasClass('list'));
console.log(new $('#list2').hasClass('foo'));
<div id="list"></div>
<div id="list2" class="foo"></div>
如果你不想在每次调用之前都放置new
,你可以在$
中使用Object.create
:
const $ = function(a, b) {
const $obj = Object.create(proto);
$obj.$el = document.querySelector(a);
return $obj;
}
const proto = {
hasClass: function(selector) {
return this.$el.classList.contains(selector);
}
};
console.log($('#list').hasClass('list'));
console.log($('#list2').hasClass('foo'));
<div id="list"></div>
<div id="list2" class="foo"></div>
我觉得jQuery的做法是,返回对象的内部原型(prototype)是$.fn
,eg:
const $ = function(a, b) {
const $obj = Object.create($.fn);
$obj.$el = document.querySelector(a);
return $obj;
};
$.fn = {
hasClass: function(selector) {
return this.$el.classList.contains(selector);
}
};
console.log($('#list').hasClass('list'));
console.log($('#list2').hasClass('foo'));
<div id="list"></div>
<div id="list2" class="foo"></div>
关于javascript - 你如何创建一个像 jquery 一样充当函数的包装器对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55682216/