Javascript 类 JQuery 库

标签 javascript jquery

我正在尝试模仿 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? 

最佳答案

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

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

关于Javascript 类 JQuery 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334607/

相关文章:

Javascript:将多个参数传递给 EventListener 和事件

javascript - Angular $http 删除请求正文

javascript - cordova inappbrowser 无法在 iOS 上打开外部 url

javascript - 为什么我从IE 11.0 客户端发布数据时得到 "GET"方法信息?

javascript - 关于 xslt 和 javascript 的查询

javascript - 使用过滤器函数从 API 返回过滤结果列表

jquery - 当 url 哈希与 div 的 id 匹配时,对该 div 的子元素执行某些操作

javascript - 获取 jQuery UI 选项卡的 URI

javascript - 如何从ajax调用中调用List<string>类型参数方法?

jquery - 如何解决在我的模板中打开页面的问题?