开发者

Is it possible to deregister Javascript prototype extension

I understand that using for..in loop to iterate over Array is not the recommended way for iteration. But I am curious to know if there is a way to deregister these extensions. I have worked with Groovy and in Groovy's case there is a registry which can be manipulated during runtime to erase the additional entries specified through metaclass.

My current use-case is that Prototype is adding extensions to Array prototype. Since I use numerous plugins based on jQuery (I do use jQuery), I have to test most functionality of the website to ensure that the everything is fine. That's quite daunting. As to why I should use Prototype and jQuery, well lets just say that, I am left with no options at the moment.

I also understand that deregistering (if possible) these extensions is in no way the solution for all the code to exist in harmony, since it means a disruptive change to the existing instances and new instances开发者_开发问答 as well. There would be numerous anonymous functions which would depend on these extensions and would fail later. I am just plain to curious to know about the javascript implementation and possible access to the underlying logic.

Thanks Ram


The problem with the for loop is that some libs (prototype) add properties to the base Object and that causes them to be enumerated by the for loop.

The following loop will loop through all the custom properties added to the base Object and delete them from the prototype, making it safe to use "for in" with arrays

for (var prop in {}) {
  delete Object.prototype[prop]   
}

However, as you have mentioned, this will break prototype itself. If you use prototype, you should use one of their iteration methods. But I didn't understand what you were trying to get at with that question so I just explained how to undo what prototype did.


The for ... in is part of the language. You can not change an existing implementation, but you can always write your own!


if you have an "foo.bar()" you can do "delete foo.bar;" and that will remove the "method" (property). Dunno if that works on prototype-inherited stuff, but it's worth a shot.


You can use Object.hasOwnProperty to determine whether the property you are looking at through iteration belongs to the array itself or its prototype. If it comes from the prototype, you can decide at that point whether to delete it or ignore it:

for property in myarray {
    if (myarray.hasOwnProperty(property)) {
        do_something_useful();
    }
}

or

for property in myarray {
    if (!myarray.hasOwnProperty(property)) {
        myarray[property] = null;
        /* or delete myarray.prototype[property] */
        /* or recursively search through prototype chain to
           find the source of property, and delete it there */
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜