扩展原语而不用原型制作它们

IT技术 javascript
2021-02-22 21:38:28

我正在开发一个非常丑陋的库,它可以让你做一些奇怪的事情。拥有一个图表,您可以以链式样式映射一组集合,并且当您更改要在整个系统中更改的值时。

当结束类型是 JS 原语时,问题就来了。

就我而言,在使用值和对象制作图形后,我可以执行以下操作:

CHAIN.components[0].value = 20; 

components是使用 setter 和 getter 对图的节点进行过滤的函数。如果组件中只有一个节点被过滤,则用户设置的默认值无需执行此操作即可使用: CHAIN.components.value = 20; 而是这样: CHAIN.components = 20;

现在的问题是,除了默认值(在我的情况下设置为value.

我怎样才能在 Number 对象上使用 setter 和 getter 而不在 Number.prototype 中进行黑客攻击,因为CHAIN.components现在是一个数字(如果它不是一个原语,我已经让它以一种不显眼的方式工作),但是当我想在CHAIN.components.func()那里打电话时是一个问题,因为func每次我制作一组或获取components然后删除它时,我都必须附加到 Number.prototype

你有其他想法来完成这种行为吗?

你想要代码,所以这里是:

/*jslint nomen: true, sloppy: true*/
GRID.modules.OHM || Object.extend(GRID.modules, ( function() {
    var Node, Nodes, Ohm, num_proto = Number.prototype.__clone(), str_proto = String.prototype.__clone();
    Node = function(uid) {
        var UID = uid;
        this.getUID = function() {
            return UID;
        };
    };
    Nodes = function() {
        var stack = [];
        this.add = function(id, val) {
            var n = new Node(stack.length);
            val.id = id;
            Object.extend(n, val);
            stack.push(n);
            return n.getUID();
        };
        this.getById = function(id) {
            return stack.filter(function(v) {
                var a = id || v.id;
                return (v.id === a);
            });
        };
        this.getByUID = function(UID) {
            return stack[UID];
        };
        this.get = function(callback) {
            !Object.isString(callback) || ( callback = [callback]);
            var f = Object.isFunction(callback) ? callback : (Object.isArray(callback) ? function(k) {
                return (callback.indexOf(k.id) >= 0);
            } : function(k) {
                return true;
            });
            return stack.filter(f);
        };
    };
    Ohm = function(n) {
        var graph = n || (new Nodes()), filters = {}, __nodes = {}, addGS = function(obj, name, conf, binder) {
            var alfa = {};
            Object.extend(alfa, conf);
            if (!alfa.get) {
                alfa.get = function() {
                    var a = this.g.getById(this.p);
                    return a.length === 1 ? a[0] : a;
                }.bind(binder);
            } else {
                alfa.get = alfa.get.bind(binder);
            }
            if (!alfa.set) {
                alfa.set = function(value) {
                    this.g.getById(this.p).forEach(function(k) {
                        Object.extend(k, value);
                        return true;
                    });
                }.bind(binder);
            } else {
                alfa.set = alfa.set.bind(binder);
            }
            Object.defineProperty(obj, name, alfa);
        }, add = function(id, node) {
            if (__nodes.hasOwnProperty(id)) {
                addGS(__nodes, id, {
                    enumerable : true
                }, {
                    t : this,
                    p : id,
                    g : graph
                });
            }
            return graph.add(id, node || {});
        };
        Object.extend(this, {
            add : function() {
                add.apply(this, arguments);
            },
            map : function(name, f, that) {
                var n = name, filterer = ['add', 'map', '__all'];
                n = Object.isFunction(n) ? name.apply(that, arguments.slice(3)) : n;
                if (filterer.indexOf(n.toLowerCase()) >= 0) {
                    console.log("You can't map over a basic property of object !!! Please read the freakin' manual.");
                    return null;
                }
                if (!filters.hasOwnProperty(n)) {
                    filters[n] = new Ohm(graph);
                    addGS(this, n, {
                        get : function() {
                            this.g.get(this.f).forEach(function(v, key, arr) {
                                var temp, binder;
                                if (arr.length !== 1) {
                                    if (!this.filt.hasOwnProperty(v.id)) {
                                        addGS(this.filt, v.id, {
                                            set : function(value) {
                                                this.t.g.getById(this.p).filter(this.t.f).forEach(function(k) {
                                                    Object.extend(k, value);
                                                });
                                            },
                                            get : function() {
                                                var a = this.t.g.getById(this.p).filter(this.t.f);
                                                return a.length === 1 ? a[0] : a;
                                            }
                                        }, {
                                            t : this,
                                            p : v.id
                                        });
                                        (key !== arr.length - 1) || Object.extend(this.filt, this.g.get(this.f));
                                    }
                                } else {
                                    if (Object.isFunction(v.__new__)) {
                                        v.__default = function() {
                                            return Object.extend((new this.__new__(arguments)), this);
                                        };
                                    }
                                    if (!Object.isUndefined(v.__default)) {
                                        temp = this.filt;
                                        this.filt = Object.isFunction(v.__default) ? v.__default.bind(v) : v.__default;
                                        if (Object.isNumber(this.filt) || Object.isString(this.filt)) {
                                            var prot = Object.isNumber(this.filt) ? Number : String;
                                            for (var i in temp) {
                                                if (temp.hasOwnProperty(i) && !prot.prototype.hasOwnProperty(i)) {
                                                    var bin = {
                                                        t : temp,
                                                        m : i,
                                                        p : prot,

                                                    };
                                                    Object.defineProperty(prot.prototype, i, {
                                                        set : function(value) {
                                                            Object.defineProperty(this.p.prototype, this.m, {
                                                                configurable : true, // defaults to false
                                                                writable : false,
                                                                value : 1
                                                            });
                                                            delete this.p.prototype[this.m];
                                                            this.t[this.m] = value;
                                                        }.bind(bin),
                                                        get : function() {
                                                            Object.defineProperty(this.p.prototype, this.m, {
                                                                configurable : true, // defaults to false
                                                                writable : false,
                                                                value : 1
                                                            });
                                                            delete this.p.prototype[this.m];
                                                            return this.t[this.m];
                                                        }.bind(bin),
                                                        enumerable : true,
                                                        configurable : true
                                                    });
                                                }
                                            }
                                        } else {
                                            Object.extend(this.filt, temp);
                                        }
                                    }
                                    if (Object.isNumber(this.filt) || Object.isString(this.filt)) {
                                        var prot = Object.isNumber(this.filt) ? Number : String;
                                        for (var i in v) {
                                            if (v.hasOwnProperty(i) && !prot.prototype.hasOwnProperty(i)) {
                                                var bin = {
                                                    t : v,
                                                    m : i,
                                                    p : prot,

                                                };
                                                Object.defineProperty(prot.prototype, i, {
                                                    set : function(value) {
                                                        Object.defineProperty(this.p.prototype, this.m, {
                                                            configurable : true, // defaults to false
                                                            writable : false,
                                                            value : 1
                                                        });
                                                        delete this.p.prototype[this.m];
                                                        this.t[this.m] = value;
                                                    }.bind(bin),
                                                    get : function() {
                                                        Object.defineProperty(this.p.prototype, this.m, {
                                                            configurable : true, // defaults to false
                                                            writable : false,
                                                            value : 1
                                                        });
                                                        delete this.p.prototype[this.m];
                                                        return this.t[this.m];
                                                    }.bind(bin),
                                                    enumerable : true,
                                                    configurable : true
                                                });
                                            }
                                        }
                                    } else {
                                        Object.extend(this.filt, v);
                                    }
                                }
                            }, this);
                            return this.filt;
                        },
                        set : function(value) {
                            this.g.get(this.f).forEach(function(k) {
                                Object.extend(k, value);
                            });
                        }
                    }, {
                        t : this,
                        f : f,
                        g : graph,
                        filt : filters[n]
                    });
                }
            }
        }, true, true);
        addGS(this, '__all', {
            get : function() {
                var a = this.g.getById();
                Object.extend(__nodes, a.length === 1 ? a[0] : a);
                return __nodes;
            },
            enumerable : true
        }, {
            t : this,
            p : null,
            g : graph
        });
    };
    window['Ω'] = Ohm;
    return {
        OHM : Ohm,
    };
}()));

现在演示:

var c = new Ω();
c.add('ann', {
__default : 58,
blah : 98,
ceva : function()
{
    console.log('asd');
}
});
c.add('ann2',{
    __default: function(){
       console.log('hello');
    },
    abc: 78,
    dce: function(){
       console.log(' world');
    }
};
c.add('b2', {
__new__ : function() {
    this.init = function() {
        this.id = 86;
    };
    this.mer = function() {
        console.log(this);
    };
},
els : 'asadar'
});
c.map('b2', function(k) {
return k.id === 'b2';
});
c.map('ann', function(k) {
return k.id === 'ann';
});
c.map('ann2', function(k) {
return k.id === 'ann2';
});
console.log(c.ann); // returns 58 ( the __default value )
console.log(c.ann.blah); // returns 98
console.log(c.ann.blah.blah); // undefined
console.log(c.ann2);  // function()
c.ann2(); // prints out 'hello'
c.ann2.cde(); // prints out 'world'
c.ann2 = 60;
console.log(c.ann2); // 60
console.log(c.ann2.cde()); // prints out 'world'

这段代码有效,但我必须使用 Number 或 String 原型的部分困扰着我。你有另一种方法吗?

原因是做一些有人说可以用 PHP 而不是 JS 的东西,这家伙最近一直在和我一起研究 WebGL 着色器,讨厌他必须编写 700 行代码才能使用多效果结合 FBO 而不是100 这会让他使用类似这样的工具,它是用 PHP 编写的。所以是的,我知道原始原型上的访问器是一种黑客,但是如果链端对象是原始对象,我如何在不必使用 valueOf 的情况下使其不同?

2个回答

好的,现在我已经阅读了附加的代码(但无法全部完成)。缺少一些评论,但我不会抱怨,我自己的代码并不好,因为我不希望有人阅读或理解它们:-)

你是对的,你扩展原生原型的部分是可怕的。据我了解,在返回数字/字符串之前,您在 Number 或 String 原型上定义了一个访问器属性。在获取和设置时,访问器属性都被数据属性 (???) 覆盖,然后在存储/返回值之前删除整个属性。这似乎是一个聪明的 hack 允许原始值的自定义属性,但是:

  • 发生碰撞的风险很高。这可能是可以通过使用以降低该this值作为查找表(区分一个关键(5).x(3).x),但它仍然不能完全避免。
  • 在访问/设置时移除自身的属性非常不直观。避免这种情况。
  • 在原语原型上随意更改访问器属性的成本很高。这是 4 个性能对比组合。没有引擎能够优化这一点。你似乎经常使用它们。

如果你真的需要这个(我仍然没有得到你的理由),我会使用一个带有查找表的变体。它应该减少冲突(不确定您的代码如何处理它们),不会更改它们定义的访问器属性,因此更持久(尽管它可能会泄漏):

// Let's call this
// PRIMITIVE PROXIES
// as they proxy real objects behind primitive values
var proxy = _.map( { // some map that works on Objects
    string: String.prototype,
    number: Number.prototype
}, function closure(type, proto) {
    var table = {};
    function setupProperty(prop) {
        if (prop in proto) return; // ah, we already proxied this kind of object
        Object.defineProperty(proto, prop, {
            configurable:true, // for deleting
            get: function getter() {
                // "this" is the primitive value
                if (!this in table)
                    return undefined;
                return table[this][prop]; // get prop from obj
            },
            set: function setter(val) {
                if (this in table)
                    table[this][prop] = val; // pass val to obj
            }
        });
    }
    return {
        create: function createProxy(prim, obj) {
            if (prim in table) // we already did create a proxy on this primitive
                return; // let's abort. You might continue to overwrite
            table[prim] = obj;
            Object.getOwnPropertyNames(obj).forEach(setupProperty);
            return prim; // the new "proxy"
        },
        move: function moveName(from, to) {
            if (to in table) return false;
            table[to] = table[from];
            delete table[from];
            return true;
        }
    };
});
proxy.create = function(prim, obj) {
    return proxy[typeof prim].create(prim, obj);
};
proxy.move = function(from, to) {
    return proxy[typeof from].create(from, to);
};
// USAGE:
// proxy.create works just like Object.extend
> var c = {ann: 58},
>     o = {blah: 98};
> proxy.create(c.ann, o);
> 58..blah
98
> c.ann.blah
98
> (58).blah = 60;
> o
{blah: 60}
> var num = c.ann; // 58
> c.ann.blah = function(){return "Hello"};
> num.blah()
"Hello"
> proxy.move(c.ann, c.ann = 78);
> c.ann
78
> (58).blah
undefined
> c.ann.blah()
"Hello"
> // getters/setters for properties are global:
> c.ann.blub = "something"; // does not work, there is no getter
> c.ann.blub
undefined
> proxy.create(58, {blub: "foo"})
> c.ann.blub // still returns
undefined
> c.ann.blub = "bar"; // but can be set now
> (58).blub + (78).blub
"foobar"
> // infinite lookup loops are possible:
> proxy.create("loop", {x:"loop"});
> "loop" === "loop".x
true
> "loop".x.x.x.….x
"loop"

但是,有一件事情您永远无法解决:

与对象不同,原始值不是唯一的;他们没有身份。

您将永远无法区分c.annfrom58"loop"from "loop".x,因此两者都会有一个属性。这不是构建 API 的好前提。

所以,我还是推荐使用NumberString对象。您不需要对它们进行子类化(如我之前的回答所示),因为您似乎没有 (m) 任何方法,因此您可以轻松构建它们:

c.ann = new Number(58);
c.ann.blah = 98;
return c;

除了typeof操作员之外,应该几乎没有区别您能否添加更多使用该__default值的示例

但是,如果链端对象是原始对象,我如何在不必使用 valueOf 的情况下使其不同?

回答这个简单的问题:那个人是对的,如果不破解原生原型,就无法在 JavaScript 中完成。你是对的,黑客很丑:-)

作为对arbitrarily changing accessor properties on the prototype of primitives are costly的答复,我不得不说我知道这一点,这实际上是我的问题。有没有另一种方法可以做同样的事情?PS我添加了更多示例。并且请不要问我这__new__件事,因为这就像用一个对象创建一个类(也就是把鸡蛋放回鸡里)。
2021-04-21 21:38:28
是的,我知道它会在第一次访问时被删除 - 这只意味着不仅ann.blah.blah不起作用,而且连续ann.blah, ann.blah. 然而,您能否详细说明对象包装器在您的代码中导致问题的位置?不应该,这是我的观点。
2021-04-21 21:38:28
实际上没有 c.ann.blah 反复工作。好吧,让我这样说,如果我将 ann 设置为一个,new Number(58)我可以毫无问题地扩展它,但是当我打电话时,c.ann它会返回一个对象而不是 58 并让它返回 58我不得不打电话valueOf困扰我的部分是丑陋部分的地图功能,我必须破解原型而不是进行扩展。我希望我不要太固执,但我希望我明白我想要完成的事情。这一切都是为了实现我的梦想(成为 JS GURU 并超越 Crockford)。
2021-04-24 21:38:28
退后一步,我是第一个:-) 老实说,我想我理解你的问题。似乎没有其他解决方案可以解决这个丑陋的问题,但我仍然不明白为什么您需要链端值是原始值(因为对象会更适合)。你有什么办法?它只是一个很好的东西,还是有任何技术限制来强制执行?
2021-05-08 21:38:28
我已经尝试过了,new Number但是在 get 我仍然会有一个对象,其中包含它的值而不是值。甚至不会有 (98).blah 因为任何其他数字都不会是原型(或者它会是但它会在我完成获取部分后被删除),所以 c.ann 将是 58 并且也会有blah 方法,但任何其他数字都不会有这种方法,因为我删除了它,我遇到了一些问题,这就是我问你的原因。如果我不删除任何集合或获取原始原型,最初 c.ann.blah.blah 就会存在。你能详细说明查找表吗?
2021-05-10 21:38:28

不要让它成为一个原始数字,让它成为一个行为像数字的对象。您可以使用一个Number对象并使用您的自定义属性对其进行扩展(请参阅https://stackoverflow.com/a/9338486/1048572),但为什么Number一般不进行子类化它只需要保留一个返回数字valueOf方法

function MyNumber(n) {
    this.value = Number(n);
}
MyNumber.prototype = Object.create(Number.prototype, {constructor:{value:MyNumber}});
MyNumber.prototype.valueOf = function() {
    return this.value;
};
// OK, we have to overwrite those methods as they don't work on subclasses of Number
["toExponential", "toFixed", "toLocaleString", "toPrecision", "toString"].forEach(function(name) {
    MyNumber.prototype[name] = function() {
        return Number.prototype[name].apply(new Number(this.value), arguments);
    };
});

// now extend the prototype with other properties, e.g. chaining methods

当然,您可能需要创建components一个将给定数字(或 Number)转换为 MyNumber 的 setter:

var actualNumber = new MyNumber;
Object.defineProperty(MyFabulousChainingThing, "components", {
    get: function() { return actualNumber; },
    set: function(x) { actualNumber.value = Number(x); }
});
@helly0d:那是不可能的,component不是只有在检查时才能决定其状态的量子力学粒子。但是,您也可以在MyNumber任何可以使用原始数字或 Number 对象地方使用实例
2021-04-20 21:38:28
好处valueOf是你不需要调用它 - 它 [也] 用于隐式类型转换:new MyNumber(9) + 1 === 10
2021-04-25 21:38:28
问题是如果component是 instanceOfMyNumber并且链在那里停止,它应该返回值,但是如果继续链,它应该进入 Node 对象内部并从那里被调用。
2021-05-08 21:38:28
问题是我也想在不调用 valueOf 的情况下使用该对象。我自己试过这种方法。所以,如果我做一个console.log(g);地方g= new MyNumber(10);,它应该返回10,但如果我不g.myFunction()工作也不必原型数(这在我的情况下做的伎俩,但在一个非常丑陋的方式)。有任何想法吗?
2021-05-16 21:38:28
请参阅我刚刚添加的代码。笑话:我想我只是成为了量子力学。
2021-05-16 21:38:28