定义了一个可以作为对象调用的函数

Defined a function that can be called as an object

本文关键字:对象 调用 函数 一个 定义      更新时间:2023-09-26

我有一个函数

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)。