how to create a function that goes after another function with this method (function1(params).function2(params)) in javascript

梦想与她 提交于 2021-02-10 14:56:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!