【问题标题】:How to handle javascript object-oriented prototype [duplicate]如何处理javascript面向对象的原型[重复]
【发布时间】:2013-06-23 07:33:20
【问题描述】:

我正在使用名为 vLine 的 js API 制作工具, 但这是javascript的基本问题,所以我在这里发布。

我想在示例代码上附加聊天系统。 我在///聊天功能

之间添加了什么

但是

this.prototype.onMessage_ 

显示错误

Uncaught TypeError: Cannot set property 'onMessage_' of undefined 

虽然我做了一些 javascript 程序,但我不擅长这个。 所以我想我不明白,一些非常基本的面向对象的javascript。

请帮帮我。

<script>
var vlineClient = (function(){
  if('{{vlineData.serviceId}}' == 'YOUR_SERVICE_ID' || '{{vlineData.serviceId}}' == 'YOUR_SERVICE_ID'){
    alert('Please make sure you have created a vLine service and that you have properly set the $serviceID and $apiSecret variables in classes/Vline.php file.');     

    }


    var client, vlinesession,
          authToken = '{{ vlineData.authToken }}',
          serviceId = '{{ vlineData.serviceId }}',
          profile = {"displayName": '{{ vlineData.displayName }}', "id": '{{ vlineData.id }}'};

    // Create vLine client  
    window.vlineClient = this.client_ = vline.Client.create({"serviceId": serviceId, "ui": true});
    // Add login event handler

 this.client_.on('login', onLogin);
    this.client_.login(serviceId, profile, authToken).done(this.init_,this);
    // Do login

   **/////chat function**
     this.prototype.onMessage_ = function(event) {
        var msg = event.message,
        sender = msg.getSender();
         console.log('get message');
        this.showAlert(sender.getDisplayName(),
                     sender.getThumbnailUrl(),
                     msg.getBody());
    };
       this.client_.on('recv:im', this.onMessage_, this);
   **/////chat function**  









  function onLogin(event) {
    vlinesession = event.target;
    // Find and init call buttons and init them
    $(".callbutton").each(function(index, element) {
       initCallButton($(this)); 
    });
  }

  // add event handlers for call button
  function initCallButton(button) {
    var userId = button.attr('data-userid');

    // fetch person object associated with username
    vlinesession.getPerson(userId).done(function(person) {
      // update button state with presence
      function onPresenceChange() {
        if(person.getPresenceState() == 'online'){
            button.removeClass().addClass('active');
        }else{
            button.removeClass().addClass('disabled');
        }
        button.attr('data-presence', person.getPresenceState());
      }

      // set current presence
      onPresenceChange();

      // handle presence changes
      person.on('change:presenceState', onPresenceChange);



      // start a call when button is clicked
      button.click(function() {
              if (person.getId() == vlinesession.getLocalPersonId()) {
            alert('You cannot call yourself. Login as another user in an incognito window');
            return;
              }
          if(button.hasClass('active'))
                            **/////chat function**
                            person.postMessage("Hello there");
                            console.log("send message");
                             **////chat function**
            person.startMedia();
      });
    });

  }

  return client;
})();





$(window).unload(function() {
  vlineClient.logout();
});

【问题讨论】:

    标签: javascript


    【解决方案1】:

    不能理解你写的很多东西。但问题很清楚。 “this”,您希望成为您的方法,但您必须非常小心,因为它会根据您执行它的位置更改上下文。

    如果我简化你的代码,它是一个模块模式的例子,应该如下。

    var moduleExample = (function () {
        // private variables and functions
        var privateVar = 'bar';
    
        // constructor
        var moduleExample = function () {
        };
    
        moduleExample.prototype.chat = function(){
            alert('hello');
        };
    
        // return module
        return moduleExample;
    })();
    
    var my_module = new moduleExample();
    my_module.chat();
    

    请注意上面的代码如何避免使用“this”。 另请注意,如何使用“new”创建新对象

    【讨论】:

      最近更新 更多