我有一个使用WeakMaps的课程如下
const myWeakMap = new WeakMap();
class myClass {
constructor(myObject) {
myWeakMap.set(this, myObject);
}
getProperty () {
return myWeakMap.get(this).property;
}
}
var instance = new myClass({property: 5});
console.log(instance.getProperty());
这在使用chrome,firefox时工作正常,但在IE上这会引发cannot read property 'property' of undefined
错误,因为myWeakMap.get(this)
是undefined
。此外,当我使用Webpack的生产构建属性时,只执行代码的uglify,系统在IE上正常工作。我不确定有什么不同或导致问题的原因,也不确定如何调试问题。欢迎任何帮助。
Webpack配置
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const BUILD_DIR_CLIENT = path.resolve(__dirname, "build-client");
const APP_DIR = path.resolve(__dirname, "src/client/main");
const SHARED_DIR = path.resolve(__dirname, "src/shared");
const extractCSS = new ExtractTextPlugin("main.css");
const extractLESS = new ExtractTextPlugin("[name].css");
const semanticCssPath = path.resolve(__dirname, "node_modules/semantic-ui-css/semantic.min.css");
const datePickerCssPath = path.resolve(__dirname, "node_modules/react-datepicker/dist/react-datepicker.css");
const elasticBuilderPath = path.resolve(__dirname, "node_modules/elastic-builder");
const ifdefOpts = {
build: process.env.BUILD_ENV,
"ifdef-verbose": true,
};
module.exports = {
entry: {
index: APP_DIR + "/client.jsx",
},
output: {
path: BUILD_DIR_CLIENT,
filename: "main_index.js",
},
module: {
rules: [
{
test: /\.less$/,
use: extractLESS.extract(["css-loader?importLoader=2&modules&localIdentName=[name]---[local]---[hash:base64:5]", "postcss-loader", "less-loader"]),
},
{
test: /\.css$/,
include: [semanticCssPath, datePickerCssPath],
use: extractCSS.extract(["css-loader"]),
},
{
test: /\.css$/,
exclude: [semanticCssPath, datePickerCssPath],
use: extractCSS.extract(["css-loader?importLoader=1&modules&localIdentName=[name]---[local]---[hash:base64:5]", "postcss-loader"]),
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: "url-loader?limit=100000",
},
{
test: /\.jsx?/,
include: [APP_DIR, SHARED_DIR, elasticBuilderPath],
use: ["babel-loader", "eslint-loader", {loader: "ifdef-loader", options: ifdefOpts}],
},
],
},
plugins: [
extractLESS,
extractCSS,
],
resolve: {
alias: {
"~": path.resolve(__dirname, "src"),
"@main": path.resolve(__dirname, "src/client/main"),
"@shared": path.resolve(__dirname, "src/shared"),
},
extensions: [".js", ".jsx", ".css", ".less"],
},
};
答案 0 :(得分:0)
写一个答案而不是评论,这样我就可以发布一些代码。
我无法重现这个问题。对我来说,以下代码在IE11和Chrome上的工作方式相同。
var myWeakMap = new WeakMap();
function myClass(myObject) {
myWeakMap.set(this, myObject);
}
myClass.prototype.getProperty = function() {
return myWeakMap.get(this).property;
};
var instance = new myClass({property: 5});
console.log(instance.getProperty());

我怀疑myClass
的构造函数在您的情况下以某种方式未定义。你能检查一下吗?为此,请在构造函数中插入console.log
,并检查日志以获取输出:
class myClass {
constructor(myObject) {
console.log("myClass.constructor", myObject);
myWeakMap.set(this, myObject);
}
// ...
}