代码之家  ›  专栏  ›  技术社区  ›  helle

javascript继承问题

  •  1
  • helle  · 技术社区  · 14 年前

    父对象发送ajax请求以发送一些联系人电子邮件。

    ajax请求被发送(也发送到正确的url),但是数据对象是空的。

    var contact_A = function(){
        var self = this;
        this.url = '/xxx/xxx/xxx';
    
        this.constructor = function(){ 
    
            this.dialog = $('.contact_box');
    
            this.sender = this.dialog.find('input[name=sender]');
            this.name = this.dialog.find('input[name=name]');
            this.content = this.dialog.find('textarea[name=content]');
    
            ...
        }
    
        this.init = function(){
           ...
           this.dialog.find('.button_blue').bind('click', function(){
               var data = self.process_form();
              if(data != false) self.send(data);
            });
            ...
        }
    
        this.process_form = function(){
    
            this.validator =  new validator('contact_box', true);
            if(this.validator.validate(true)) {
    
                var data = {
                    sender: this.sender.val(),
                    name: this.name.val(),
                    content: this.content.val()
                }
    
                return data;
            } else return false;
        }
    
        this.send = function(data){
    
            $.ajax({
                type: "POST",
                url: self.url,
                data: data,
                success: function(msg){
                    //if not successful
                    self.successful(msg);
                },
                async: true
            });
    
            this.close();
        }
    
        ...
    
        this.constructor();
        this.init();
    }
    

    这是继承对象:

    var conteact_B = function(){
        var self = this;
        this.constructor();
        this.init();    
    }
    conteact_B.prototype = new contact_A;
    conteact_B.prototype.url = '/yyy/yyy/yyy';
    
    1 回复  |  直到 14 年前
        1
  •  0
  •   Community CDub    8 年前

    将对象的原型样式与对象的闭包样式混合在一起。这不太管用。

    问题是:

    var contact_A = function(){
        var self = this;
        ... do stuff with self ...
    };
    
    conteact_B.prototype = new contact_A;
    

    self 永远是什么 this new contact_A 自己 将始终是原型对象,而不是 contact_B 实例。

    自己 constructor .

    this discussion 作为背景。