The global objects in wechat applet are different from those in other environments. There is a big gap between the global objects obtained by global and V8 JavaScript engine, which requires compatibility in many cases.

The problem

The main development language of small program is JavaScript, and the development of small program is very similar to the common web development. Moving from web development to applets is not expensive for front-end developers, but there are a few differences.

The anti-shock code added to the native wechat applet project via yarn Add Lodash. Debounce does not run directly.

// => TypeError: Cannot read property 'now' of undefined
Copy the code

This is because the way LoDash gets global objects does not work in wechat applets

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global= ='object' && global && global.Object === Object && global;
// => global.Object is undefined 

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
// => freeSelf is undefined 

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this') ();// => root => {}

var now = function() {
  return root.Date.now();
};
// => root.Date is undefined
Copy the code

The solution

// lodash-polyfill.js
var g = typeof window! = ='undefined' &&
window.Math === Math ? window : typeof global= = ='object' ? global : this

if(! g.Object) { g.Object =Object
}

if(! g.Date) { g.Date =Date
}
Copy the code
// app.js
require('./lodash-polyfill.js')
Copy the code

This way, you can happily use Lodash. Debounce in your project.


Welcome to follow my wechat official account: The Coder of wind and waves