类似Javascript JQuery的库

Javascript JQuery-like library

本文关键字:的库 JQuery Javascript 类似      更新时间:2023-09-26

我试图模仿JQuery库(用于学习目的),但我遇到了以下问题:

function _(id){
var about={
version:"1.0",
author:"Samson"
}
if (this===window)
    return new _(id);
if (!id) 
    return about;
if (typeof id=="string")
    this.element=document.getElementById(id);
else
    this.element=id;
return this;
}
_.prototype={
    append:function(str){
        this.element.innerHTML+=str;
        return this;
    },
    post:function(url){
        alert('posting to: '+url);
    }
}

我可以这样使用:

_("a1").append(' deescription');

但我希望能够在不调用构造函数的情况下使用post函数:

_.post('url') //post is in the prototype but is undefined because the constructor is not called right? 

您需要在_本身而不是其原型上定义post

_.post = function(url) { ... }