我正在尝试模仿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?
答案 0 :(得分:4)
您需要在post
本身定义_
,而不是原型。
_.post = function(url) { ... }