简体   繁体   中英

How do I override javascript's cloneNode?

This is what I have so far: http://jsfiddle.net/beCVL/5/

This is how I'm trying to override the default cloneNode: Object.defineProperty(Object.prototype, "cloneNode", { get: cloneNode2, set: cloneNode2 });

but it's not working, so, I think Object.prototype doesn't have cloneNode, but Element.prototype doesn't either.

So, which class do I need to use to override cloneNode, assuming my method is correct?

Try using:

Node.prototype.cloneNode = cloneNode2;

Object.defineProperty is not used for this purpose. Here's an example of a use for it:

var o = {};
Object.defineProperty(o, 'blah', {
    'get': function () { return 'asdf'; },
    'set': function (x) { alert(x); }
});

alert(o.blah); // alerts 'asdf'
o.blah = 'fdsa'; // alerts 'fdsa'

Apparently, this only works in Chrome.

To solve the actual problem, it should be simple enough to just replace the RGB codes with its equivalent hex code.

function decToHex(a) {
    return ('00' + (+a).toString(16)).substr(-2);
}
function replaceRGB(str) {
    return str.replace(/rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/, function (_, r, g, b) {
        return "#" + decToHex(r) + decToHex(g) + decToHex(b);
    });
}
replaceRGB("color: rgb(255, 0, 0)") // "color: #ff0000"

It's a property of Node.prototype https://developer.mozilla.org/En/DOM/Node.cloneNode

Node.prototype.cloneNode = function() {}

However, modifying built in objects may give you grief in the future. If possible, you should create a different function and use that instead, that way, existing code that uses cloneNode won't break.

This series of fiddles is a work in progress, but it reimplements cloneNode's functionality. http://jsfiddle.net/beCVL/19/

as of April 4th, 10:53am EST, it needs to work with IE, as IE doesn't have a Node object.

Note, that in IE, prototype functions can't be overridden. So, all instances of cloneNode have to be replaced by a function that determines which version of cloneNode to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM