Javascript 以 jquery 方式继承
Javascript inheritence in jquery way
如果我在一个对象下设置一个函数,我只能使用它一次,比如
function handle(selector)
{
return{
elem:selector,
next:function(){
return (this.nextSibling.nodeType==1) ? this.nextSibling : this.nextSibling.nextSibling;
}
}
}
这里我可以说 handle.next()
这会起作用,但如果我想说 handle.next().next().next()
我的问题是我如何像 jquery 那样使用这种方式?
说到你的函数,你可以像这样修改它以使其工作:
function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
return{
elem:selector,
next:function(){
return handle(selector.nextElementSibling);
}
}
}
参见jsfiddle。
更新:修改代码以支持元素和字符串选择器作为参数。
UPD 2:推出了另一种变体。在这种情况下,我们扩展原生 html 元素对象并添加新的 next 方法:
function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
selector.next = function() {
return handle(selector.nextElementSibling);
};
return selector;
}
Fiddle 是 here.
如果我在一个对象下设置一个函数,我只能使用它一次,比如
function handle(selector)
{
return{
elem:selector,
next:function(){
return (this.nextSibling.nodeType==1) ? this.nextSibling : this.nextSibling.nextSibling;
}
}
}
这里我可以说 handle.next()
这会起作用,但如果我想说 handle.next().next().next()
我的问题是我如何像 jquery 那样使用这种方式?
说到你的函数,你可以像这样修改它以使其工作:
function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
return{
elem:selector,
next:function(){
return handle(selector.nextElementSibling);
}
}
}
参见jsfiddle。
更新:修改代码以支持元素和字符串选择器作为参数。
UPD 2:推出了另一种变体。在这种情况下,我们扩展原生 html 元素对象并添加新的 next 方法:
function handle(selector)
{
if (typeof selector === 'string') {
selector = document.querySelector(selector);
}
selector.next = function() {
return handle(selector.nextElementSibling);
};
return selector;
}
Fiddle 是 here.