策略
- 特性检测:通过检测运行环境中是否存在特定的全局对象或特性来调整代码行为。例如,在浏览器环境中存在
window
对象,而在 Node.js 环境中存在 global
对象。
- 使用 Polyfill:对于一些在不同环境中实现不一致或者低版本环境不支持的特性,使用 Polyfill 来提供统一的实现。
- 避免使用环境特定的全局变量:尽量不依赖特定环境的全局变量,而是通过参数传递等方式获取所需的对象或值。
代码示例
示例一:检测全局对象
function MyConstructor() {
// 获取全局对象
const globalObject = typeof window!== 'undefined'? window : typeof global!== 'undefined'? global : this;
// 在此处使用 globalObject 进行操作
globalObject.someProperty = 'value';
}
示例二:使用 Polyfill(以 Object.assign
为例)
// 如果环境不支持 Object.assign,添加 Polyfill
if (typeof Object.assign!== 'function') {
Object.assign = function(target) {
'use strict';
if (target === null || target === undefined) {
throw new TypeError('Cannot convert undefined or null to object');
}
let output = Object(target);
for (let index = 1; index < arguments.length; index++) {
let source = arguments[index];
if (source!== null && source!== undefined) {
for (let key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
output[key] = source[key];
}
}
}
}
return output;
};
}
function AnotherConstructor() {
let obj1 = { a: 1 };
let obj2 = { b: 2 };
let result = Object.assign(obj1, obj2);
// 使用 result 进行后续操作
}