JS问题,尝试给window添加全局变量,但是报错了

小刘
  • 526

问题描述

我希望给window里面添加MobileWindow,然后这个MobileWindow作为全局变量,其他的函数能够访问到,但是报错了

具体代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .t1 {
      width: 500px;
      height: 200px;
      background: #0C9A9A;
    }
  </style>
</head>
<body>

<div>
  <div class="t1">
    按钮
  </div>
</div>

<script>

  (function(){
    MobileWindow.prototype = {
      name: 123
    }
    window.MobileWindow = MobileWindow
  })()

  window.onload = function () {
    initClickEven()
  }

  function initClickEven() {
    document.getElementsByClassName('t1')[0].onclick = function () {
      console.log('t1');
      console.log(MobileWindow.name);
    }
  }

</script>
</body>
</html>

感谢楼下提供思路

方案1

<script>

  (function(){
    // function MobileWindow () {
    //
    // }
    // MobileWindow.prototype = {
    //   name: 123
    // }
    // window.MobileWindow = MobileWindow
    window.MobileWindow = Object.create({name: 325})
  })()

  window.onload = function () {
    initClickEven()
  }

  function initClickEven() {
    document.getElementsByClassName('t1')[0].onclick = function () {
      console.log('t1');
      console.log(MobileWindow.name);
    }
  }

</script>

方案2

<script>

  (function(){
    function MobileWindow () {

    }
    MobileWindow.prototype = {
      name: 123
    }
    window.MobileWindow = MobileWindow
    // window.MobileWindow = Object.create({name: 325})
  })()

  window.onload = function () {
    initClickEven()
  }

  function initClickEven() {
    document.getElementsByClassName('t1')[0].onclick = function () {
      console.log('t1');
      // console.log(MobileWindow.name);
      console.log(new MobileWindow().name);
    }
  }

</script>
回复
阅读 762
3 个回答
✓ 已被采纳
 (function () {
   window.MobileWindow = function () {};
   MobileWindow.prototype = {
     name: 123,
   };
 })();

 window.onload = function () {
   initClickEven()
 };

 function initClickEven() {
   console.log(new MobileWindow().name);
 }

我猜你想要的是这种?

  (function(){
    MobileWindow = {
      name: 123
    }
    window.MobileWindow = MobileWindow
  })()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏