javascript - 我想编写一个具有良好结构的代码。但我不能

标签 javascript function class prototype literals

我想编写一个具有良好结构的代码,如下所示: 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 设置”附近存在问题。 但我不知道如何解决它。 请帮助我。

最佳答案

try this

您遇到了 3 个问题:

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

应该是:

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

  });

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

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

    myFriend.getInfo();
    
  • 关于javascript - 我想编写一个具有良好结构的代码。但我不能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34986473/

    相关文章:

    javascript - 在 ReactJS 组件中定义事件处理程序的正确方法是什么?

    javascript - 使用什么 lint 配置来消除警告 : Invalid JSDoc tag name

    c++ - 为什么堆栈溢出会导致总线错误 10 而不是段错误

    PHP 类未正确回显

    python - 什么是实现多个构造函数的干净 "pythonic"方式?

    Java:如何让对象监听器在不同的类中工作?

    javascript - Ember 幻影 : faker output reuse in record creation

    if else 语句中的 JavaScript 变量

    python - Python中参数的强制命名

    c++ - 在函数中返回带有 2 个可选构造函数的对象