我想制作一个结构良好的代码.但我不能

I wanna make a code that has nice structural. But I can't

本文关键字:代码 不能 结构 一个      更新时间:2023-09-26

我想制作一个结构很好的代码,如下所示:https://github.com/nolimits4web/Swiper/blob/master/dist/js/swiper.jquery.js#L67

所以,我做了这个。但它不起作用。http://jsbin.com/xiralokola/edit?html,js,output

// friends.js
$(function () {
  'use strict';
  
  function Friends() {
    var settings = {
      name: null,
      age: null,
      gender: null,
      printTarget: null
    };
  }
  
  Friends.prototype = {
    getInfo: function () {
      var subject = (this.gender == 'female') ? 'She' : 'He',
          html = '<p>';
      html += '''' + this.name + ''' is my friend.';
      html += subject + ' is' + this.age + ' years old.';
      html += '</p>';
      
      this.printTarget.append(html);
      return html;
    }
  };
  
  window.Friends = Friends;
  
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Friends</title>
</head>
<body>
  
  <h1>Friends</h1>
  <div id="print"></div>
  <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <script src="friends.js"></script>
  <script>
    var myFriend = new Friends({
      name: 'Hee-sook',
      age: 15,
      gender: 'female', 
      printTarget: $('#print')
    });
  </script>
  
</body>
</html>

我认为"var 设置"附近存在问题。但我不知道如何解决它。请帮助我。

试试这个

您有 3 个问题:

  1. 在定义之前,您已经尝试调用 Friends 的实例(在这种情况下,(函数)应该在 html 上,而不是在 js 文件上)

应该是:

<script>
$(function () {
var myFriend = new Friends({
  name: 'Hee-sook',
  age: 15,
  gender: 'female', 
  printTarget: $('#print')
});
  });

  1. 您没有将设置对象传递给构造函数,应该是:

    function Friends(settings) {
        $.extend(this,settings);
    }
    
  2. 您没有在实例上调用 getInfo():

    myFriend.getInfo();
    
相关文章: