定义了一个可以作为对象调用的函数
Defined a function that can be called as an object
我有一个函数
function obj(id){
if (this.__proto__.constructor !== i) {
return new i(id);
}
this.element = (typeof id === 'string') ? document.getElementById(id) : id;
this.remove = function(){
this.element.parentNode.removeChild(this.element);
}
this.cookie = function (name,value,expire){
var now = new Date();
var time = now.getTime();
time += expire*1000; //in second
now.setTime(time);
document.cookie = name + '=' + value + '; expires=' + now.toUTCString() + '; path=/';
}
}
我可以像调用obj("someid").remove();
一样调用方法remove
,但是调用cookie
方法。函数cookie不依赖于id
。
如何定义对象obj
,以便以obj(id).remove()
和obj.cookie()
两种方式调用其方法?
看起来应该是这样的:
function obj(id) {
if (!(this instanceof obj)) return new obj(id);
this.element = (typeof id === 'string') ? document.getElementById(id) : id;
}
obj.prototype.remove = function() {
this.element.parentNode.removeChild(this.element);
};
obj.cookie = function(name,value,expire) {
var now = new Date();
var time = now.getTime();
time += expire*1000; //in second
now.setTime(time);
document.cookie = name + '=' + value + '; expires=' + now.toUTCString() + '; path=/';
};
函数(如obj
) 是对象,因此您可以简单地为其添加属性(如.cookie
)。
相关文章:
- 从联合js rect对象调用引导模式
- 为什么可以't我用Set对象调用Array.prototype.map
- 从数组(JS)中的对象调用函数
- 在CouchDB Map函数中发出日期时-对日期对象调用的内容
- 'stepUp'对未实现接口HTMLInputElement的对象调用
- 从设置为原型的对象调用属性
- 类型错误:'单击'对未实现接口HTMLElement的对象调用
- 从javascript对象调用函数
- 得到"未捕获的类型错误:未定义的不是函数“;当试图从对象调用get()或set()时
- 子对象调用兄弟姐妹'方法
- 是否可以在函数构造函数中识别哪个对象调用它,并在错误的对象调用时中止创建
- Angularjs:错误:'追加'对未实现接口FormData的对象调用.jQuery.param/ad
- 为什么这个带有对象调用函数的Javascript setInterval在传入回调时不计算内部参数
- 生成自定义对象调用
- 对非对象调用了gulp jscs Object.keys
- JavaScript 从子对象调用父函数
- 对字符串对象调用 .localeCompare 与构造特制的 Intl.Collator 对象之间的性能差异
- 一次将所有对象调用到函数中,返回每个对象的特定计算
- 不能从jquery对象调用的Javascript方法
- 从具有事件侦听器的对象调用函数