The WeChat applet cannot access the window. How to add global top-level methods or properties? Direct global top-level call!

As we all know, there are many encapsulated methods for wx objects in small programs. We can directly call them globally through wx.$name. So how do we define top-level objects or methods like this ourselves? 

In traditional browsers, there is a top-level window object. We can directly inject our global methods or properties into it, but this does not work in small programs because we cannot directly access the window object globally. Although you can develop Get it from the console of the tool.

But we can find another way. Since there is no window object, we can find Object!!, after all“Everything in js is an object” a>, the top level of the prototype chain is our Object, so we can do this

Object.defineProperty(Object.prototype, "Zero", {
  value: {
    dateFormat(time) {
      let date = new Date(time);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let h = date.getHours();
      let i = date.getMinutes();
      let s = date.getSeconds();
      return y + "-" + m + "-" + d + " " + h + ":" + i + ":" + s;
    },
  },
  configurable: false,
  enumerable: false,
});

 Of course, we can also add our own methods directly to the wx object, and even make some modifications and extensions to its native methods.

Object.defineProperty(wx, "dateFormat", {
  value() {
    function dateFormat(time) {
      let date = new Date(time);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let h = date.getHours();
      let i = date.getMinutes();
      let s = date.getSeconds();
      return y + "-" + m + "-" + d + " " + h + ":" + i + ":" + s;
    }
    return dateFormat.apply(this, arguments);
  },
  configurable: false,
  enumerable: false,
});

 After that, we can directly use it globally, which is very useful for some special scenarios.

 

Guess you like

Origin blog.csdn.net/SAXX2/article/details/132691507