问题
how can I make this possible?
function _(element) {
var el = document.querySelector(element);
return el;
}
function colorize(color) {
this.style.color = color;
}
_("#myElement").colorize("#f0f0f0");
that this code first gets the element and then changes its text color. How to make sth like this?????
回答1:
_("#myElement")
returns an instance of Element. You can add colorize
property to Element.prototype
. Now, all objects of type Element
will be able to call it:
function _(element) {
var el = document.querySelector(element);
return el;
}
function colorize(color) {
this.style.color = color;
}
Object.assign(Element.prototype, { colorize })
_("#redText").colorize("red");
_("#greenText").colorize("green");
<span id="redText">Red</span>
<span id="greenText">Green</span>
It's a bit more verbose but prototypes are usually extended using Object.defineProperty
so that they are not enumerated as a property:
Object.defineProperty(Element.prototype, 'colorize', {
value: colorize
})
来源:https://stackoverflow.com/questions/62345915/how-to-create-a-function-that-goes-after-another-function-with-this-method-func