javascript - js压缩混淆后,其他文件怎么引用相关方法

查看:606
本文介绍了javascript - js压缩混淆后,其他文件怎么引用相关方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

1.压缩前的js

(function () {
  var Test = function (name, age) {
    this.name=name;
    this.age=age;
  }
  Test.prototype={
    getName:function () {
      return this.name + ' haha';
    }
  }
  var testA = new Test('xiao',12)  // 这里获取得到 Test对象
  console.log(testA.getName());
})()

2.压缩后的js

!function(){var e=function(e,n){this.name=e,this.age=n};e.prototype={getName:function(){return this.name+" haha"}};var n=new e("xiao",12);console.log(n.getName())}();

3.在html中引入压缩后的js后,

var testA = new Test('xiao', 12)   // 这里找不到 Test对象
  console.log(testA.getName());

请问一下,js代码压缩前要怎么改写才能解决这个问题?

解决方案

(function () {
 // ....
})() 

这种写法,内部的变量是不会暴露出来的,外部是引用不到的,这样写可以防止全局变量被污染。
如果需要暴露给外部,可以改为

(function () {
  var Test = function (name, age) {
    this.name=name;
    this.age=age;
  }
  Test.prototype={
    getName:function () {
      return this.name + ' haha';
    }
  }
  window.Test = Test
})()

如果不想直接暴露给全局变量,担心有冲突,也可以这么写

window.myModule = {}

(function () {
  var Test = function (name, age) {
    this.name=name;
    this.age=age;
  }
  Test.prototype={
    getName:function () {
      return this.name + ' haha';
    }
  }
  window.myModule.Test = Test 
})()

这篇关于javascript - js压缩混淆后,其他文件怎么引用相关方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆